Assignment by reference

March 8th, 2005. Tagged: PHP certification

In this section, the curious reader might wonder about the combination of assignment by reference and a simple arithmetic operation such as addition. OK, let's take a step back.

Consider this:
< ?php $a = 10; $b = $a; $a = 20; echo $b; ?>
In this example the output will be 10, because the value of $a was passed to $b and that's it. Whatever happens to $a after that, $b doesn't want to know.
This was an illustration of the most common case in everyday's programming, passing by value.

Now about passing by reference.
< ?php $a = 10; $b = &$a; $a = 20; echo $b; ?>
In this case the output will be 20, because a reference to the value of $a was assigned to $b. In other words, $b was just a nickname for $a. Continuing with the nickname analogy, let's say Jon is a nickname for the little boy Jonathan. Jonathan went out to play. After the game Jonathan got really dirty. Can we say that Jon was dirty? Yes, we can. It doesn't matter how we refer to that little fella, we won't get any cleaner.

Now how about passing the result of an arithmetic operation as a reference, like this:
< ?php $a1 = 10; $a2 = 20; $b = &$a1 + &$a2; $a1 = 300; echo $b; ?>
The answer is - you cannot do this. You'll get a parse error message from the PHP interpreter.
The same will happen if you try:
$b = &($a1 + $a2);
$b = &($a1 + 1);
$b = 1 + &$a2;

What you can do though is
$b = &$a1 + $a2;
although it will not work as one may expect. In this example $b will become a nickname for $a1 only. $a2 will be ignored completely. In the following example:
< ?php $a1 = 10; $a2 = 20; $b = &$a1 + $a2; echo $b; $a1 = 300; echo $b; ?>
the first echo will print 10, which is the value of $a1 and the second echo will print 300.

In conclusion, the value of only one variable is passed when using reference. Passing by reference cannot be combined with other (e.g. arithmetic) operations.

< ?php $b = &&$a; ?>

will also cause an error. At the end, does it make sense? Passing the reference of the reference to a variable?

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov