的PHP documentation說,下面講__call()
魔術方法:在PHP觸發__call(),即使存在方法
__call()在對象範圍內調用方法不可訪問時被觸發。
有沒有一種方法可以讓__call()
即使在方法存在時調用實際方法?或者,有沒有其他的我可以實現的鉤子或者其他可以提供這種功能的方法?
如果很重要,這是一個static function
(我實際上更喜歡使用__callStatic
)。
的PHP documentation說,下面講__call()
魔術方法:在PHP觸發__call(),即使存在方法
__call()在對象範圍內調用方法不可訪問時被觸發。
有沒有一種方法可以讓__call()
即使在方法存在時調用實際方法?或者,有沒有其他的我可以實現的鉤子或者其他可以提供這種功能的方法?
如果很重要,這是一個static function
(我實際上更喜歡使用__callStatic
)。
如何讓所有其他方法受到保護,並通過__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();
我喜歡這個。當我升級到PHP 5.3時,我會記住這一點。謝謝。 – 2009-07-10 19:38: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'
這是完美:) – nXqd 2013-02-14 14:02:17
參見:http://stackoverflow.com/questions/3241949/how-to-catch- any-method-call-on-object-in-php – Benubird 2013-05-01 13:38:50