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?

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.