As with PHP7, you can do
$obj = new StdClass; $obj->fn = function($arg) { return "Hello $arg"; }; echo ($obj->fn)('World');
or use Closure :: call () , although this does not work on StdClass .
Before PHP7, you need to implement the magic __call method to intercept the call and call the callback (which is not possible for StdClass , of course, because you cannot add the __call method)
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');
Note that you cannot do
return call_user_func_array(array($this, $method), $args);
in the body of __call , because it will call __call in an infinite loop.
Gordon Dec 26 '10 at 20:55 2010-12-26 20:55
source share