PHP documentation说明__call()
魔术方法:
在对象上下文中调用不可访问的方法时会触发__ call()。
在调用实际方法之前,即使方法存在,我是否可以调用__call()
?或者,是否有其他可以实现的钩子或其他提供此功能的方法?
如果重要,则适用于static function
(我实际上更愿意使用__callStatic
)。
答案 0 :(得分:21)
为什么不让所有方法受到保护并使用__call()调用它们:
class bar{
public function __call($method, $args){
echo "calling $method";
//do other stuff
//possibly do method_exists check
return call_user_func_array(array($this, $method), $args);
}
protected function foo($arg){
return $arg;
}
}
$bar = new bar;
$bar->foo("baz"); //echo's 'calling foo' and returns 'baz'
答案 1 :(得分:11)
如何保护所有其他方法,并通过__callStatic代理它们?
namespace test\foo;
class A
{
public static function __callStatic($method, $args)
{
echo __METHOD__ . "\n";
return call_user_func_array(__CLASS__ . '::' . $method, $args);
}
protected static function foo()
{
echo __METHOD__ . "\n";
}
}
A::foo();