Calling closure assigned to object property directly

前端 未结 12 2260
孤街浪徒
孤街浪徒 2020-11-22 14:02

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

12条回答
  •  自闭症患者
    2020-11-22 14:44

    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.

提交回复
热议问题