- iPhone (2)
- Learning (42)
- Linux (4)
- Debian (1)
- Mac Terminal / Linux (5)
- Other Stuff (1)
- Programming (66)
- Slim Framework (1)
- Uncategorized (4)
- WordPress (5)
We participate in the Amazon Service LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
This one tests your knowledge of how reference variables work:
$a = 'P'; $b = &$a; $b = "PH$b";
What will $a and $b be after these three lines of code run?
First, $a is set to ‘P’. Then, $b gets a reference to the variable $a.
Next, $b is set to ‘PH’ followed by the value of $b, which is a reference to $a, so it becomes “PHP”.
However, keep in mind that it works both ways. Now that we set $b to “PHP”, $a will also the same because $b is a reference to $a.
This means that a reference variable is a two way street. Change either and they are both affected.
It just so happened that the initial value of $a was pulled into the assignment on the third line first, and then the entire value ended up in $a afterward. But how?
Remember that $b is a pointer to the address of the contents of $a. So, when we assign $b, we are actually affecting the memory location that $a sits at.
So it first read the value of $a, then overwrite it with the new string. The first letter of the new string is sitting in the same memory location that contained the original “P”, and now has two more letters following it.
Technically, the contents of $b is still just an address internally – the address of $a.