直接调用分配给对象属性的闭包 [英] Calling closure assigned to object property directly

查看:30
本文介绍了直接调用分配给对象属性的闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够调用我直接分配给对象属性的闭包,而无需将闭包重新分配给变量然后调用它.这可能吗?

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?

下面的代码不起作用并导致致命错误:调用未定义的方法 stdClass::callback().

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();

推荐答案

从 PHP7 开始,你可以做到

As of PHP7, you can do

$obj = new StdClass;
$obj->fn = function($arg) { return "Hello $arg"; };
echo ($obj->fn)('World');

或使用 Closure::call(),虽然那没有处理 StdClass.

or use Closure::call(), though that doesn't work on a StdClass.

在 PHP7 之前,你必须实现神奇的 __call 方法来拦截调用并调用回调(这对于 StdClass 当然是不可能的,因为你不能添加 __call 方法)

Before PHP7, you'd have to implement the magic __call method to intercept the call and invoke the callback (which is not possible for StdClass of course, because you cannot add the __call method)

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');

注意你不能这样做

return call_user_func_array(array($this, $method), $args);

__call 主体中,因为这会在无限循环中触发 __call.

in the __call body, because this would trigger __call in an infinite loop.

这篇关于直接调用分配给对象属性的闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆