Pass by Reference
suggest changeThis allows you to pass a variable by reference to a function or element that allows you to modify the original variable.
A reference returned from a function can also be passed by reference.
A new expression cannot. foo(new SomeClass) raises Notice: Only variables should be passed by reference and does not give the function a reference it can modify.
Arrays
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 prefixing the variable with an &, as in &$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 by unset()’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 the issues that can result from this is present in this question on StackOverflow.
Functions
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. On current PHP,
foo(&$a)is a parse error (unexpected token "&").