Calling closure assigned to object property direct

2018-12-31 20:13发布

I would like to be able to call a closure that I assign to an object's property directly without reassigning the closure to a variable and then calling it. Is this possible?

The code below doesn't work and causes Fatal error: Call to undefined method stdClass::callback().

$obj = new stdClass();
$obj->callback = function() {
    print "HelloWorld!";
};
$obj->callback();

11条回答
高级女魔头
2楼-- · 2018-12-31 20:58

You can do this by calling __invoke on the closure, since that's the magic method that objects use to behave like functions:

$obj = new stdClass();
$obj->callback = function() {
    print "HelloWorld!";
};
$obj->callback->__invoke();

Of course that won't work if the callback is an array or a string (which can also be valid callbacks in PHP) - just for closures and other objects with __invoke behavior.

查看更多
有味是清欢
3楼-- · 2018-12-31 20:58

Here's another alternative based on the accepted answer but extending stdClass directly:

class stdClassExt extends stdClass {
    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}

Usage example:

$foo = new stdClassExt;
$foo->blub = 42;
$foo->whooho = function () { return 1; };
echo $foo->whooho();

You are probably better off using call_user_func or __invoke though.

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 21:00

Well, if you really insist. Another workaround would be:

$obj = new ArrayObject(array(),2);

$obj->callback = function() {
    print "HelloWorld!";
};

$obj['callback']();

But that's not the nicest syntax.

However, the PHP parser always treats T_OBJECT_OPERATOR, IDENTIFIER, ( as method call. There seems to be no workaround for making -> bypass the method table and access the attributes instead.

查看更多
ら面具成の殇う
5楼-- · 2018-12-31 21:00

well, it should be emphisized that storing the closure in a variable, and call the varible is actually (wierdly) faster, depending on the call amount, it becomes quite a lot, with xdebug (so very precise measuring), we are talking about 1,5 (the factor, by using a varible, instead of directly calling the __invoke. so instead , just store the closure in a varible and call it.

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 21:01

As of PHP 7 you can do the following:

($obj->callback)();
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 21:02

Since PHP 7 a closure can be called using the call() method:

$obj->callback->call($obj);

Since PHP 7 is possible to execute operations on arbitrary (...) expressions too (as explained by Korikulum):

($obj->callback)();

Other common PHP 5 approaches are:

  • using the magic method __invoke() (as explained by Brilliand)

    $obj->callback->__invoke();
    
  • using the call_user_func() function

    call_user_func($obj->callback);
    
  • using an intermediate variable in an expression

    ($_ = $obj->callback) && $_();
    

Each way has its own pros and cons, but the most radical and definitive solution still remains the one presented by Gordon.

class stdKlass
{
    public function __call($method, $arguments)
    {
        // is_callable([$this, $method])
        //   returns always true when __call() is defined.

        // is_callable($this->$method)
        //   triggers a "PHP Notice: Undefined property" in case of missing property.

        if (isset($this->$method) && is_callable($this->$method)) {
            return call_user_func($this->$method, ...$arguments);
        }

        // throw exception
    }
}

$obj = new stdKlass();
$obj->callback = function() { print "HelloWorld!"; };
$obj->callback();
查看更多
登录 后发表回答