What You Need to Know About PHP References

References can be quite confusing in PHP. Or for that matter, when learning any other programming language. One thing’s for sure: they are very handy.

So, what is a PHP reference, you might ask?

A reference, quite simply, is a method to refer to the content of a particular variable just by using another name. One simple example of a reference could be file shortcuts in Windows.

Now, creating a PHP reference is simple. Consider the following code given below:

 myphpnet1 $myVar = “Hi there”;

2 $anotherVar =& $myVar;

3 $anotherVar = “See you later”;

4 echo $myVar; // Displays “See you later”

5 echo $anotherVar; // Displays “See you later”

In line 2, if you notice an ampersand (&) attached to the equal sign, this allows you to create a reference. If you don’t add that symbol, the output could be the one as assigned in line 1. In other words, line 4 would display “Hi there”.

What this reference does is merely point to the value in $myVar instead of making two copies of the same string. Also, when you change $anotherVar, this is also reflected in $myVar as well. This will not take place if line 2 read as: “2 $anotherVar = $myVar”.

It should be noted that if line 3 read as: ‘3 $myVar = “See you later”;’, the resulting output in line 4 and 5 would be no different.

If you want to remove the values in the original variable and the one used as a reference, then you will have to use the unset() command. In other words, you should remove all references made to that variable.

In the example above, here’s what you should do to reset the values in memory.

1 $myVar = “Hi there”;

2 $anotherVar =& $myVar;

3 $anotherVar = “See you later”;

4 unset( $anotherVar );

5 unset( $myVar );

6 echo $myVar; // Displays “”