6.4.5. References
When you assign an object to another variable, you create a copy:
$fred = new Person;
$copy = $fred;
$fred->name("Fred");
print $copy->name(); // does not print "Fred"
You now have two Person objects,
$fred and $copy, with
independent property values. This is also the case when you assign
the results of a call to a constructor, as shown here:
$fred = new Person;
The object created by the Person constructor is
copied, and the copy is stored in $fred. This
means that $this in the constructor and
$fred actually refer to two different objects. If
the constructor creates an alias to $this through
a reference, it won't create an alias to
$fred. For example:
$people = array();
class Person {
function Person () {
global $people;
$people[] =& $this;
}
}
$fred = new Person;
$fred->name = "Fred";
$barney =& new Person;
$barney->name = "Barney";
var_dump($people);
array(2) {
[0]=>
&object(person)(0) {
}
[1]=>
&object(person)(1) {
["name"]=>
string(6) "Barney"
}
}
$fred is a copy of the object that the constructor stored in
$people[0], while $barney is an alias for the object that the
constructor stored in $people[1]. When we change the properties of
$fred, we're not changing the object that is in
$people[0]. However, when we change the properties of $barney, we are
changing the object in $people[1].
To prevent copying on assignment, assign by reference:
$obj =& new Class;
This code makes $obj an alias for the new object,
which was $this in the constructor. If the
constructor stores a reference to $this, it keeps
a reference to $obj.
The documentation for a class should say whether you need to use
=& with its constructor. In most cases, this
isn't necessary.