Home > Backend Development > PHP Tutorial > Why Can't I Directly Call an Object's Closure Property in PHP, and How Can I Fix It?

Why Can't I Directly Call an Object's Closure Property in PHP, and How Can I Fix It?

DDD
Release: 2024-12-17 18:30:10
Original
382 people have browsed it

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!";
};
Copy after login

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');
Copy after login

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');
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template