Assigning variables by value and reference
Posted by Paula (Paula), 25 October 2005Hi,
I've just seen this example regarding the assigning of variables by value and by reference.
$variable1 = "Ryan";
$variable2 = $variable1; // assign by value
print( "$variable1, $variable2<br>" ); // prints "Ryan, Ryan"
$variable2 = "Scott";
print( "$variable1, $variable2<br>" ); // prints "Ryan, Scott"
$variable3 = &$variable1; // assign by reference
print( "$variable1, $variable3<br>" ); // prints "Ryan, Ryan"
$variable3 = "Katie";
print( "$variable1, $variable3<br>" ); //prints "Katie, Katie"
I don't understand how this works. That the ampersand makes the variable take its original value makes sense - it's that the variable it's resetting - variable1 - was never changed.
Should the line reading "$variable3 = &$variable1;" not be "$variable3 = &$variable2;" for this example to work?
Posted by admin (Graham Ellis), 25 October 2005Hi, Paula ... welcome to Opentalk.
A good question on an oft-confusing subject.
If you assign a variable in the "normal" way, you're copying the contents of the variable so that you end up with another variable and another copy of the value. Change one of the two variables created in this way, and you've only changed that one.
If you use the extra & character, you're assigning a second name to the same variable .... so that if you change the contents via either name, both variables will apparently be changed; really, they're the same variable though ... with two names.
Posted by Paula (Paula), 25 October 2005Ah! Now it makes sense!
How would such a thing be useful though?
Thanks a lot,
Posted by admin (Graham Ellis), 25 October 2005It's useful because you can write a whole lot of complicated code to deal with a variable such as "$current", then point $current at each of the elements of an array you want to process in turn ... welcome to the beginnings of the OO world
Posted by Paula (Paula), 26 October 2005Mmmm, that sounds dead useful. Thanks a lot for that.
PH: 01225 708225 • FAX: 01225 793803 • EMAIL: firstname.lastname@example.org • WEB: http://www.wellho.net • SKYPE: wellho