In the above code, if I were to echo out $szVar2, what would its value be? If you'd have said to me WiredFlame.com then you'd have been dead wrong, sadly. Surprisingly, TalkPHP.com is the correct answer. Even though we're assigning the value of TalkPHP.com to $szVar1, because we've made $szVar1 as a reference to $szVar2, we can effectively now control $szVar2 as well.
Passing by reference is really quite simple on the face of it. You're not assigning $szVar1 the value of $szVar2, which would have been WiredFlame.com. You are assigning it $szVar2 as a reference.
Essentially now, when $szVar1 changes, $szVar2 follows suit.
You may ask why this is useful. Well, the chances are you've blissfully been using PHP functions out-of-the-box and they've been accepting variables or arrays as reference. These are the functions that just work, they do not return anything, usually - which means you do not have to catch the function's return value like so:
$aArray = array_pop($aArray);
Albeit some will still return true and false. What you normally do is:
Your $aArray will then be changed for you. This is a good example of an array being passed as a reference, and not by its value.
A good example where you could use passing by reference, is in the foreach loop. Most people would do the following:
As we are passing the elements in by reference, from the array, we can set them just by assigning $szItem to the action we wish to perform. PHP will handle the rest and change all the items in our array for us! How so very clever is that?
Of course, you may also pass by reference in functions. This is done like so:
if(count($aArray) == 0)
foreach($aArray as &$szItem)
$szItem .= '.';
You see, we've even gone the extra mile and added in a return as true or false. This can be checked like so:
if(array_add_fullstop($aArray) === true)
// Do something fancy!
// Do some disastrous!
You don't need to worry about the array because if the function has returned true then your array has been modified to include the full-stops at the end of each array element.
Passing by reference, as you can see, need not be a complex topic. It's pretty straightforward as aforementioned. The next time you see the ampersands (&) prepended to variables and arrays, as well as in function arguments and loops, just remember, whatever the topic, complex or not, TalkPHP.com is the next best thing to having Albert Einstein sat next to you when you're doing your Maths homework. That'll show those condescending teachers!
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.