1

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?

Erdss4
  • 1,025
  • 3
  • 11
  • 31

1 Answers1

2

$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();
Alex Granados
  • 136
  • 1
  • 8
  • Thank you for clearing that up. If an anonymous function had lots of calls to it and it alters content of `$this` could they start to overlap, is that even possible? – Erdss4 May 29 '20 at 13:47