By default, variables are passed to functions by value, not by reference. The following example:
<?php function doublevalue($var) { $var = $var * 2; } $variable = 5; doublevalue($variable); echo '$variable is: '.$variable; #Prints: $variable is: 5
The parameter $variable
that is passed to the function doublevalue()
isn’t changed by the function. What actually happens is that the value 5 is passed to the function, doubled to 10, and the result is lost forever (as we didn’t return the value). The value is passed to the function, not the variable itself.
Passing arguments by reference
<?php function doublevalue(&$var){ $var = $var * 2; } $variable = 5; doublevalue($variable); echo '$variable is: '. $variable; #Prints: $variable is: 10
The only difference between this example and the last one is that the parameter $var
to the function doublevalue()
is prefixed with an ampersand character: &$var
. The ampersand means that a reference to the original variable is passed as the parameter, not just the value of the variable. The result is that changes to $var
in the function affect the original variable $variable
outside the function.
Assigning PHP variables by reference
Referencing with the ampersand can also be used when assigning variables, which allows the memory holding a value to be accessed from more than one variable. This example illustrates the idea:
<?php $x = 10; $y = &$x; $y++; echo $x; # Prints: 11 echo $y; # Prints: 11
Because $y
is a reference to $x
, any change to $y
affects $x
. In effect, they are the same variable. So, by adding 1 to $y
, you also add 1 to $x
, and both are equal to 11.
The reference $y
can be removed with the unset($y)
command, this has no effect on $x or its value.
User-defined functions: