从PHP7开始,您可以
$obj = new StdClass;
$obj->fn = function($arg) { return "Hello $arg"; };
echo ($obj->fn)('World');
或使用Closure ::call(),尽管不适用于StdClass
。
在PHP7之前,您必须实现magic __call
方法来拦截调用并调用回调(StdClass
当然不可能,因为您无法添加该__call
方法)
class Foo
{
public function __call($method, $args)
{
if(is_callable(array($this, $method))) {
return call_user_func_array($this->$method, $args);
}
// else throw exception
}
}
$foo = new Foo;
$foo->cb = function($who) { return "Hello $who"; };
echo $foo->cb('World');
请注意,您不能做
return call_user_func_array(array($this, $method), $args);
在__call
体内,因为这会触发__call
无限循环。