This allows you to pass a variable by reference to a function or element that allows you to modify the original variable.
Passing-by-reference is not limited to variables only, the following can also be passed by reference:
foo(new SomeClass)
A common use of "passing-by-reference" is to modify initial values within an array without going to the extent of creating new arrays or littering your namespace. Passing-by-reference is as simple as preceding/prefixing the variable with an &
=> &$myElement
.
Below is an example of harnessing an element from an array and simply adding 1 to its initial value.
$arr = array(1, 2, 3, 4, 5);
foreach($arr as &$num) {
$num++;
}
Now when you harness any element within $arr
, the original element will be updated as the reference was increased. You can verify this by:
print_r($arr);
Note
You should take note when harnessing pass by reference within loops. At the end of the above loop,
$num
still holds a reference to the last element of the array. Assigning it post loop will end up manipulating the last array element! You can ensure this doesn't happen byunset()
'ing it post-loop:$myArray = array(1, 2, 3, 4, 5); foreach($myArray as &$num) { $num++; } unset($num);
The above will ensure you don't run into any issues. An example of issues that could relate from this is present in this question on StackOverflow.
Another common usage for passing-by-reference is within functions. Modifying the original variable is as simple as:
$var = 5;
// define
function add(&$var) {
$var++;
}
// call
add($var);
Which can be verified by echo
'ing the original variable.
echo $var;
There are various restrictions around functions, as noted below from the PHP docs:
Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.