Reference challenge

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.

Leave a Reply

Your email address will not be published. Required fields are marked *