PHP References

A Powerful, But Tricky, Feature of PHP

Articles > Webmaster > PHP References

The PHP language defaults to assignment and parameter passing by value. This means that when you use the = operator to assign a variable or pass a record as an argument to a function, the original record is copied rather than being used directly.

To help understand this, imagine that we start out with a 37-year-old man named Fred, and then we age him using a function and rename him using a temporary variable:

$x = new Person("Fred", 37);

function agePerson($person, $years) {
  $person->age += $years;
}
agePerson($x, 10);

$y = $x;
$y->name = "Barney";

echo "x is named $x->name and is $x->age years old.";

x is named Barney and is 47 years old.

As you can see from the previous example, the agePerson() function only aged a private copy of Fred, leaving the original untouched. Similarly, changing the name of $y to Barney has no effect on the record stored in $x.

If we use the PHP & operator to create references, however, all of this changes:

$x = new Person("Fred", 37);

function reallyAgePerson(&$person, $years) {
  $person->age += $years;
}
reallyAgePerson($x, 10);

$y =& $x;
$y->name = "Barney";

echo "x is named $x->name and is $x->age years old.";

x is named Barney and is 47 years old.

The $person variable inside the function now refers to the same value slot as the $x variable outside the function, and so when the function changes $person, $x also changes. Similarly, $x and $y are now referring to the same value slot, so changing $y also changes $x.

All of this will be familiar to anybody who programs in C, C++, Java, or any other language that uses pointers. References are not pointers, however, as the following example illustrates:

$x = new Person("Fred", 37);

$y =& $x;
$y = 42;

echo "x is $x.";

x is 42.

If we tried to say echo "x is named $x->name and is $x->age years old." the script would crash, since $x is a number now, and numbers do not have fields.

If you want to learn more, see why you might want to use references, what the reference-using PHP would look like, and what the most common mistake looks like. You might also be interested in a visual illustration of how references work.