2013-01-07 35 views
2

可能重複:
Magic __get getter for static properties in PHPPHP抓調用靜態參數

是否有可能趕上調用​​這樣的靜態參數:

class foo 
{ 
    public static $foo = 1; 
    //public static $bar = 2; 

    public function catch_bar_call() 
    { 
     print "Calling an undefined property"; 
    } 
} 


print foo::$foo //1 
print foo::$bar //error 

代替出現錯誤,我想要調用一個方法。 我知道它可能的槽__get()魔術方法,但你必須爲此類實例化你的類,而不是靜態參數。

+0

我看到它,也許有人知道一個解決方案... –

回答

0

From PHP DOC

$ name參數是正在互動與屬性的名稱。 __set()方法的$ value參數指定$ name'ed屬性應該設置的值。

屬性重載只能在對象上下文中使用。 這些神奇的方法不會在靜態環境中觸發。因此這些方法不應該被聲明爲靜態的。從PHP 5.3.0開始,如果其中一個魔術重載方法聲明爲靜態,則會發出警告。

什麼,我覺得你可以做的是

class Test { 
    private static $foo = 1; 
    // public static $bar = 2; 
    public static function foo() { 
     return self::$foo; 
    } 

    public static function __callStatic($n,$arg) { 
     print "\nCalling an undefined property $n"; 
    } 
} 
echo "<pre>"; 
print Test::foo(); // 1 
print Test::bar(); // Calling an undefined property bar 

輸出

1 
Calling an undefined property bar 
+0

處理該問題wihile調用靜態函數,但不調用靜態參數/屬性。嘗試Test :: $ bar(它沒有設置並引發錯誤,我想要的是設置一種偵聽器來捕獲屬性/參數上的所有調用,並在屬性不持久時作出反應) –