How to call a closure that is a class variable?

Answer from StackOverflow

In PHP, methods and properties are in a separate namespace (you can have a method and a property with the same name), and whether you are accessing a property or a method depends of the syntax you are using to do so.

$expr->something() is a method call, so PHP will search for a method in the class.

$expr->something is a property fetch, so PHP will search for a property in the class.

$myInstance->lambda(); is parsed as a method call, so PHP searches for a method named lambda in your class, but there is no such method (hence the Call to undefined method error).

So you have to use the fetch property syntax to fetch the lambda, and then call it.

  • You can do this with ->lambda->__invoke():
$myInstance = new MyClass();
$myInstance->lambda->__invoke();

__invoke is one of PHP’s magic methods. When an object implements this method, it becomes invokable: it can be called using the $var() syntax. Anonymous functions are instances of Closure, which implements __invoke.
- Or assign it to a local variable:

$lambda = $myInstance->lambda;
$lambda();

Or call it using call_user_func:

call_user_func($myInstance->lambda);

call_user_func can call any callable, including anonymous functions.
Alternatively, if this is a common pattern in your code, you can setup a __call method to forward calls to your lambda:

class MyClass
{
    private $lambda;

    public function __construct()
    {
        $this->lambda = function() {
            echo "Hello world!\n";
        };
    }

    public function __call($name, $args)
    {
        return call_user_func_array($this->$name, $args);
    }
}

Now this works:

$myInstance = new MyClass();
$myInstance->lambda();

Since PHP 5.4 you can even do that in a trait:

trait LambdasAsMethods
{
    public function __call($name, $args)
    {
        return call_user_func_array($this->$name, $args);
    }
}

class MyClass
{
    use LambdasAsMethods;

    private $lambda;

    public function __construct()
    {
        $this->lambda = function() {
            echo "Hello World!\n";
        };
    }
}

$myInstance = new MyClass();
$myInstance->lambda();

Reference

http://stackoverflow.com/questions/7067536/how-to-call-a-closure-that-is-a-class-variable

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值