Calling closure assigned to object property directly

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

    If you're using PHP 5.4 or above you could bind a callable to the scope of your object to invoke custom behavior. So for example if you were to have the following set up..

    function run_method($object, Closure $method)
    {
        $prop = uniqid();
        $object->$prop = \Closure::bind($method, $object, $object);
        $object->$prop->__invoke();
        unset($object->$prop);
    }
    

    And you were operating on a class like so..

    class Foo
    {
        private $value;
        public function getValue()
        {
            return $this->value;
        }
    }
    

    You could run your own logic as if you were operating from within the scope of your object

    $foo = new Foo();
    run_method($foo, function(){
        $this->value = 'something else';
    });
    
    echo $foo->getValue(); // prints "something else"
    

提交回复
热议问题