note 10178 deleted from language.references.whatdo by sniper

From: Date: Tue, 30 Sep 2003 01:20:32 +0000
Subject: note 10178 deleted from language.references.whatdo by sniper
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-57325@lists.php.net to get a copy of this message
Note Submitter: tbutzon@imawebdesigner.com ---- This explaination is for those who don't understand how creating an object by reference without doing it a certain "proper" way actually creates two objects. Question: How does creating a _reference_ (which is only supposed to create an alias, not a copy) to an object end up creating a _copy_ of the object? Answer: When you instantiate a class whose constructor returns a reference to the newly-instantiated object... function &myClass() { //...some code... return $this; } ..., but without assigning the object by reference... $myObj = new myClass() ..., PHP does the following: 1) Creates a new object using myClass 2) Executes the object's myClass() constructor 3) myClass() returns a reference to $this 4) Because $myObj is not being assigned by reference, however, $myObj ends up being a _copy_ of the originally-created object. 5) After the execution of the myClass() constructor, there is no longer any reference to the original myClass object. (As opposed to while it was executing, when there was the $this variable referencing it.) Having no more references to it, the first object is now deleted from memory, and you are left with a copy of it in $myObj. However, if the assignment had been done by... $myObj =& new myClass(); ..., a reference would've been made to the first instantiation of the object instead of it being copied. You may find it helpful to refer to: An example script's source: http://imawebdesigner.com/ext-doc/assignbyref.phps The example script's output: http://imawebdesigner.com/ext-doc/assignbyref-output.txt

« previous php.notes (#57325) next »