What are references? References are a tool in PHP that we can use to access the content of a variable through several identifiers ("names"). When a reference is modified, the content it points to will be changed directly, this means that when editing a reference or the original variable we change it for everything referencing that content simultaneously. To put it into context, say you had set up a company, and you applied for a P.O. Box for your office. You would then have two addresses, which point to the same place. References are like the P.O. box, they are "addresses" through which we can modify the content of a variable. In terms of code we could have a variable called $var and then make a reference to it called $vartwo, when $var is edited, $vartwo also changes and vica versa. References are created using "reference binding" this is very similar to assignment, but uses =& (equals ampersand) to tell the PHP parser that we are creating a reference and not a new variable. Below is an example of creating and using references to manipulate variables:
<?php
// Create a normal variable.
$var = 5;
// Make a reference to $var
$vartwo =& $var;
// Increment $vartwo
$vartwo++;
// Output $var
echo $var;
// Outputs "6"
?>
When creating references, it is important to remember that you can only create references to variables, and not to content. This is because until the content is placed inside a variable, it has no address. Taking our previous metaphor, this would be like trying to get mail sent to you as "Joe Bloggs, no fixed address" it can't be done because no one knows where you are! Therefore, the following code is invalid:
<?php
// Try to create a new reference:
$reference =& 'text string';
?>
This will in fact, return a syntax error like "Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting T_NEW or T_STRING or T_VARIABLE or '$'", because PHP cannot make a reference to unassigned values. It would be valid however if we first assigned 'text string' to a variable, and made a reference to that variable.