Home >Backend Development >PHP Tutorial >Why Can't I Directly Call an Object's Closure Property in PHP, and How Can I Fix It?
Calling Object Property Closure Directly
When assigning a closure to an object's property, you may encounter difficulties calling it directly without reassigning the closure to a variable. Consider the following example:
$obj = new stdClass(); $obj->callback = function() { print "HelloWorld!"; };
Unfortunately, attempting to call $obj->callback() will result in the error "Fatal error: Call to undefined method stdClass::callback()".
PHP 7 Solution
In PHP 7, using arrow functions (introduced in PHP 7.4), you can directly invoke a closure assigned to an object's property as follows:
$obj = new StdClass; $obj->fn = function($arg) { return "Hello $arg"; }; echo ($obj->fn)('World');
Closure::call()
For versions of PHP below 7, an alternative is to use the Closure::call() function. However, this method is not applicable to StdClass instances.
Magic __call Method
Before PHP 7, a viable approach was to implement the magic __call method, which allows intercepting calls to undefined methods. In the following example, a Foo class is created with an __call implementation:
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 the __call implementation avoids infinite recursion by preventing the same method from being called within the __call body.
The above is the detailed content of Why Can't I Directly Call an Object's Closure Property in PHP, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!