PHP 5.4 - 'closure $this support'

前端 未结 4 1690
生来不讨喜
生来不讨喜 2020-11-29 01:03

I see that the new planned features for PHP 5.4 are: traits, array dereferencing, a JsonSerializable interface and something referred to as \'closure $this support

4条回答
  •  悲哀的现实
    2020-11-29 01:45

    One thing that Gordon missed is re-binding of $this. While what he described is the default behaviour, it is possible to re-bind it.

    Example

    class A {
        public $foo = 'foo';
        private $bar = 'bar';
    
        public function getClosure() {
            return function ($prop) {
                return $this->$prop;
            };
        }
    }
    
    class B {
        public $foo = 'baz';
        private $bar = 'bazinga';
    }
    
    $a = new A();
    $f = $a->getClosure();
    var_dump($f('foo')); // prints foo
    var_dump($f('bar')); // works! prints bar
    
    $b = new B();
    $f2 = $f->bindTo($b);
    var_dump($f2('foo')); // prints baz
    var_dump($f2('bar')); // error
    
    $f3 = $f->bindTo($b, $b);
    var_dump($f3('bar')); // works! prints bazinga
    

    The closures bindTo instance method (alternatively use the static Closure::bind) will return a new closure with $this re-bound to the value given. The scope is set by passing the second argument, this will determine visibility of private and protected members, when accessed from within the closure.

    • PHP: Closure
    • Blog post: Closure Object Binding in PHP 5.4

提交回复
热议问题