2011-08-22 134 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手册中偶然发现了这种方法,但是,正如您所提到的,只有在调用一个不存在的静态方法时才会调用它。 –