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

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

问题描述

我想能够调用一个闭包,直接分配给一个对象的属性,而不将闭包重新分配给一个变量,然后调用它。这是可能吗?

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 c $ c>。

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


推荐答案



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 当然,因为你不能添加 __调用方法)

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

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

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