phpoopanonymous-functionphp-closures

PHP automatic binding of $this, is it a copy or an extend?


When using an anonymous PHP function that is defined inside a class context, the docs say "the current class is automatically bound to it, making $this available inside of the function's scope".

But I'm a little confused what that means, does it mean the anonymous function has a copy of the class or is it now part of the class? So if I use the anonymous function to make changes to the class, they will stay in the original class where the anonymous function was defined?


Solution

  • $this variable inside anonymous function in PHP is not a copy, is a binding, so if you alter the content of $this inside the anonymous function, the parent class would be affected.

    You can check it running this snippet:

    class Foo
    {
        private $test = 1;
    
        function __construct()
        {
            $func = function() {
                $this->test = 2;
            };
            $func();
            var_dump($this);
        }
    };
    
    new Foo();