Home > Backend Development > PHP Tutorial > How to Directly Invoke Closures Assigned to Object Properties in PHP?

How to Directly Invoke Closures Assigned to Object Properties in PHP?

Susan Sarandon
Release: 2024-12-09 17:28:11
Original
974 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template