Calling closure assigned to object property directly

前端 未结 12 2354
孤街浪徒
孤街浪徒 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 15:03

    Here's another alternative based on the accepted answer but extending stdClass directly:

    class stdClassExt extends stdClass {
        public function __call($method, $args)
        {
            if (isset($this->$method)) {
                $func = $this->$method;
                return call_user_func_array($func, $args);
            }
        }
    }
    

    Usage example:

    $foo = new stdClassExt;
    $foo->blub = 42;
    $foo->whooho = function () { return 1; };
    echo $foo->whooho();
    

    You are probably better off using call_user_func or __invoke though.

提交回复
热议问题