简体   繁体   中英

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?

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM