Author Topic: Understanding Variable Reference; Code Sequence  (Read 248 times)

Chris

  • Regular Member
  • **
  • Posts: 26
  • Karma: 1
    • View Profile
Understanding Variable Reference; Code Sequence
« on: January 20, 2012, 02:22:47 PM »
Hello,

First of all, I'd just like to say that this forum is awesome! I'm a total programming newbie asking questions which have been sufficiently explained.

As I'm learning,  really want to know the nuances of how the codes "operate", not just settling for "that's just the way it works".

In that regard, I have this questions about assigning a variable to another variable (did I define that right?). I believe it is called REFERENCING?

PHP Code: [Select]
<?php
$firstVar 
'nice day!';           
$secondVar = &$firstVar;            
$secondVar "Have a  $secondVar";  
echo 
$firstVar;
echo 
$secondVar;  
?>


...which outputs: Have a nice day! Have a nice day!

I sort of get the idea that the $firstVar is referenced via $secondVar.

What's really confusing to me is the echos. It's like the code is reading and echoing backwards from the last $secondVar to the middle and then $firstVar.

Shouldn't the first echo $firstvar output "nice day! Have a" ? Obviously it is not, so I'd like to know how the code "thinks".

Thanks in advance.
Chris

Smokey PHP

  • Web Developer
  • Expert PHP Helper
  • Senior Member
  • *****
  • Posts: 618
  • Karma: 9
    • View Profile
Re: Understanding Variable Reference; Code Sequence
« Reply #1 on: January 20, 2012, 03:07:20 PM »
When you create a reference using &$var, the variable you assign it to holds the value of $var and becomes a new "route" for assigning new values to $var:

PHP Code: [Select]
$firstVar 'nice day!';
/*
* $secondVar is initalised with the value of $firstVar (as normal, when the & is not used).
* Placing the & in front of $firstVar creates a reference, meaning that now when you type $secondVar,
* it's the same as typing $firstVar. The only difference, being that the value is still being applied to
* $secondVar along with $firstVar.
*/
$secondVar = &$firstVar//$secondVar now equals "nice day!"
$secondVar "Have a $secondVar"//Gives $secondVar "Have a nice day!" (as it's a reference to $firstVar, that value also changes)
/*
* The following 2 lines have the exact same result as the single line above
* whether the & was used or not
*/
$firstVar "Have a $secondVar";
$secondVar "Have a $secondVar";


If you think of a 'reference' variable being set, as 2 separate commands it should be easier to think of the process in which it is done.

Chris

  • Regular Member
  • **
  • Posts: 26
  • Karma: 1
    • View Profile
Re: Understanding Variable Reference; Code Sequence
« Reply #2 on: January 20, 2012, 05:12:57 PM »
Like I said: Awesome!

Thanks again, SMOKEY PHP!

Chris