![]() |
Lowdown on Passing Things as Reference
As a boy of 18 learning PHP, many tutorials over-complicated the PHP passing by reference side of things and just became all too puzzling to say the least. Let's start us off with a little quiz.
PHP Code:
$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: PHP Code:
true and false. What you normally do is:PHP Code:
$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: PHP Code:
PHP Code:
$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: PHP Code:
true or false. This can be checked like so:PHP Code:
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! |
| All times are GMT. The time now is 05:52 PM. |
Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0