2011-08-22 39 views
5

幾個月前,我已閱讀了有關每次調用靜態方法時都調用的PHP函數,類似於實例化類的實例時調用的__construct函數。但是,我似乎無法找到哪個函數在PHP中處理此功能。有這樣的功能嗎?PHP中靜態方法的構造函數替代

回答

6

您可以__callStatic()玩,做這樣的事情:

class testObj { 
    public function __construct() { 

    } 

    public static function __callStatic($name, $arguments) { 
    $name = substr($name, 1); 

    if(method_exists("testObj", $name)) { 
     echo "Calling static method '$name'<br/>"; 

     /** 
     * You can write here any code you want to be run 
     * before a static method is called 
     */ 

     call_user_func_array(array("testObj", $name), $arguments); 
    } 
    } 

    static public function test($n) { 
    echo "n * n = " . ($n * $n); 
    } 
} 

/** 
* This will go through the static 'constructor' and then call the method 
*/ 
testObj::_test(20); 

/** 
* This will go directly to the method 
*/ 
testObj::test(20); 

使用此代碼由「_」將運行靜態的構造函數'之前第一任何方法。 這只是一個基本的例子,但您可以使用__callStatic,但它對您更好。

祝你好運!

+0

這不是我所希望的,但我認爲它與我所尋找的最接近。謝謝,阿迪。 –

+0

沒問題,希望我幫忙。 –

3

的__callStatic()被調用每次你調用不存在的類的靜態方法。

+0

前段時間,我在PHP手冊中偶然發現了這種方法,但是,正如您所提到的,只有在調用一個不存在的靜態方法時纔會調用它。 –

相關問題