Php By Reference

前端 未结 5 906
夕颜
夕颜 2020-12-17 06:03

Can someone please explain what the \"&\" does in the following:

class TEST {

}

$abc =& new TEST();

I know it is by reference. Bu

5条回答
  •  独厮守ぢ
    2020-12-17 06:40

    As I understand it, you're not asking about PHP references in general, but about the $foo =& new Bar(); construction idiom.

    This is only seen in PHP4 as the usual $foo = new Bar() stores a copy of the object. This generally goes unnoticed unless the class stored a reference to $this in the constructor. When calling a method on the returned object later on, there would be two distinct copies of the object in existence when the intention was probably to have just one.

    Consider this code where the constructor stores a reference to $this in a global var

    class Bar {
        function Bar(){
           $GLOBALS['copy']=&$this;
            $this->str="hello";
        }
    
    }
    
    //store copy of constructed object
    $x=new Bar;
    $x->str="goodbye";
    
    echo $copy->str."\n"; //hello
    echo $x->str."\n"; //goodbye
    
    //store reference to constructed object
    $x=&new Bar;
    $x->str="au revoir";
    
    echo $copy->str."\n"; //au revoir
    echo $x->str."\n"; //au revoir
    

    In the first example, $x and $copy refer to different instances of Foo, but in the second they are the same.

提交回复
热议问题