简体   繁体   English

$this和&$this在php5中有什么区别

[英]What is the difference in php5 between $this and &$this

I have some confusion about $this and &$this, please describe this point.我对 $this 和 &$this 有一些困惑,请描述这一点。

Update:更新:

Thanks for reply.谢谢您的回复。 I know about pass by value and pass by reference.我知道按值传递和按引用传递。 Please see the following program.请参阅以下程序。

/////////////////////////////////////////////////////
class my_class
{
    var $my_var;
    function my_class ($var)
    {
        global $obj_instance;
        $obj_instance = $this;
        $this->my_var = $var;
    }
}
$obj = new my_class ("something");
echo $obj->my_var;
echo $obj_instance->my_var;
////////////////////////////////////

In this program $obj_instance = $this;在这个程序$obj_instance = $this; is copy the variable but output of this somethingsomething but when I am using $obj_instance = &$this;是复制变量但是 output 这个东西但是当我使用$obj_instance = &$this; the output is somethings. output 是什么东西。 Why is it different?为什么不一样?

Thank you.谢谢你。

This is expected behavior.这是预期的行为。 Quoting http://php.net/manual/en/language.references.whatdo.php :引用http://php.net/manual/en/language.references.whatdo.php

If you assign a reference to a variable declared global inside a function, the reference will be visible only inside the function.如果您将引用分配给在 function 内声明为全局的变量,则该引用将仅在 function 内可见。 You can avoid this by using the $GLOBALS array.您可以通过使用 $GLOBALS 数组来避免这种情况。

and thus the result of your code is just "something".因此您的代码的结果只是“某事”。 It will also emit a notice about "Trying to get property of non-object" (when error reporting is enabled).它还将发出有关“尝试获取非对象的属性”的通知(启用错误报告时)。

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

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