Home >Backend Development >PHP Tutorial >How to Directly Invoke Closures Assigned to Object Properties in PHP?
Invoking Closures Assigned to Object Properties Directly
In PHP, closures assigned to object properties have limitations when attempting to invoke them directly. As demonstrated in the provided code:
$obj = new stdClass(); $obj->callback = function() { print "HelloWorld!"; }; $obj->callback();
This code fails with the error "Fatal error: Call to undefined method stdClass::callback()." To resolve this, PHP 7 introduced a direct invocation method.
PHP 7 and Above
In PHP 7 and later, you can invoke closures assigned to object properties directly using the following syntax:
$obj = new stdClass; $obj->fn = function($arg) { return "Hello $arg"; }; echo ($obj->fn)('World');
Pre-PHP 7
Before PHP 7, invoking closures assigned to object properties directly was not possible. Instead, you needed to implement the magic __call method to intercept the call and invoke the closure:
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: In __call, it's crucial to avoid calling call_user_func_array(array($this, $method), $args); as this will trigger infinite recursion.
The above is the detailed content of How to Directly Invoke Closures Assigned to Object Properties in PHP?. For more information, please follow other related articles on the PHP Chinese website!