几个月前,我已经读过每次调用静态方法时调用的PHP函数,类似于__construct实例化类实例时调用的函数.但是,我似乎无法在PHP中找到什么函数来处理这个功能.有这样的功能吗?
您可以使用__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);
Run Code Online (Sandbox Code Playgroud)
使用此代码,任何以'_'开头的方法都将首先运行静态'构造函数'.这只是一个基本的例子,但你可以使用,__callStatic但它对你来说效果更好.
祝好运!