[Previous] [Contents] [Next]


Assigning by reference

Referencing with the ampersand can also be used when assigning variables, which allows the memory holding a value to be accessed from more than one variable. This example illustrates the idea:

$x = 10;
$y = &$x;
$y++;
echo $x;
echo $y;

Here's how it prints:

11
11

Because $y is a reference to $x, any change to $y affects $x. In effect, they are the same variable. So, by adding 1 to $y, you also add 1 to $x, and both are equal to 11.

The reference $y can be removed with:

unset($y);

This has no effect on $x or its value.


[Previous] [Contents] [Next]