开发者

What is the difference in php5 between $this and &$this

I have some confusion about $this and &$this, please describe this point .

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; is copy the variable but output of this somethingsomething but when I am using $obj_instance = &$this; the output is somethings. Why is it different?

Thank you.


This is expected behavior. Quoting 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. You can avoid this by using the $GLOBALS array.

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜