简体   繁体   English

PHP $this的自动绑定,是copy还是extend?

[英]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".当使用在 class 上下文中定义的匿名 PHP function 时,文档说“当前的 class 自动绑定到它,使$this在函数范围内可用”。

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?但我有点不明白这是什么意思,这是否意味着匿名 function 有 class 的副本,或者它现在是 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?因此,如果我使用匿名 function 对 class 进行更改,它们将保留在定义匿名 function 的原始 class 中吗?

$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. PHP 中匿名 function 中的$this变量不是副本,而是绑定,因此如果更改匿名 function 中$this的内容,父 class 将受到影响。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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