$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
$szVar1as a reference to
$szVar2, we can effectively now control
Passing by reference is really quite simple on the face of it. You're not assigning
$szVar1the value of
$szVar2, which would have been WiredFlame.com. You are assigning it
$szVar2as a reference.
Essentially now, when
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:
false. What you normally do is:
$aArraywill 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:
$szItemto 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:
false. This can be checked like so:
truethen 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!