In PHP we often have complex collections like arrays that may be difficult to use. We can use references to more easily test and mutate arrays.
With a reference we can avoid indexing the array repeatedly, and just use a variable. This can simplify programs. Often functions can benefit from reference parameters.
Here we see a function that receives a variable reference argument. When modify()
assigns the reference, this changes the variable at the calling location.
string
ends up with the value "blue."function modify(&$color) { // Modify a function parameter that is a reference. $color = "blue"; } $test = "red"; modify($test); // This is now modified. var_dump($test);string(4) "blue"
Creating references to variables like integers is probably less useful in PHP programs, but it helps illustrate the concept.
var_dump
statement prints 20 because the original value was changed from 10 to 20 through an assignment to the reference.// Step 1: create a variable and an alias (reference) to it. $value = 10; $alias =& $value; // Step 2: modify the variable through the reference variable. $alias = 20; // Step 3: the original was changed by modifying the reference. var_dump($value);int(20)
Suppose we want to act upon an array element. For clearer code, we can reference the array element and use the reference directly.
string
"red" is at index 1 (the second element).// Step 1: create an array of strings. $colors = ["blue", "red", "orange"]; // Step 2: get a reference to the second element in the array. $red =& $colors[1]; var_dump($red); // Step 3: modify the array through the reference variable. $red = "crimson"; var_dump($colors);string(3) "red" array(3) { [0]=> string(4) "blue" [1]=> &string(7) "crimson" [2]=> string(6) "orange" }
By creating references in our PHP programs, we can make functions more powerful. And we can change elements in arrays with simpler syntax.