Calling closure assigned to object property directly

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

    I know this is old, but I think Traits nicely handle this problem if you are using PHP 5.4+

    First, create a trait that makes properties callable:

    trait CallableProperty {
        public function __call($method, $args) {
            if (property_exists($this, $method) && is_callable($this->$method)) {
                return call_user_func_array($this->$method, $args);
            }
        }
    }
    

    Then, you can use that trait in your classes:

    class CallableStdClass extends stdClass {
        use CallableProperty;
    }
    

    Now, you can define properties via anonymous functions and call them directly:

    $foo = new CallableStdClass();
    $foo->add = function ($a, $b) { return $a + $b; };
    $foo->add(2, 2); // 4
    

提交回复
热议问题