Calling closure assigned to object property directly

前端 未结 12 2352
孤街浪徒
孤街浪徒 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:51

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

提交回复
热议问题