PHP Pass by Reference
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:
New statements, e.g. foo(new SomeClass)
References returned from functions
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.
Now when you harness any element within $arr, the original element will be updated as the reference was increased. You can verify this by:
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:
Another common usage for passing-by-reference is within functions. Modifying the original variable is as simple as:
$var = 5;
Which can be verified by echo'ing the original variable.
There are various restrictions around functions, as noted below from the PHP docs:
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.