Understanding Variable Reference; Code Sequence

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]<?php
$firstVar = ‘nice day!’;
$secondVar = &$firstVar;
$secondVar = “Have a $secondVar”;
echo $firstVar;
echo $secondVar;
?>[/php]

…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

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]$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”;
    [/php]

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.

Like I said: Awesome!

Thanks again, SMOKEY PHP!

Chris

Sponsor our Newsletter | Privacy Policy | Terms of Service