Entry
What does an ampersand (&) before a function parameter do?
How can I pass a variable by reference to a function?
Jun 6th, 2002 12:54
Brandon Tallent, Nathan Wallace, Chad Cunningham
It passes the variable by reference, which is to say that rather than
passing the function the contents of the variable, it passes the memory
address of the variable instead.
See function -> Passing by Reference -> Arguments in:
http://www.php.net/manual/control-structures.php3
This is typically used if the function needs to modify more than one
variable. Take a function that swaps two variables as an example:
function swap(&$var_1, &$var_2)
{
$temp = $var_1;
$var_1 = $var_2;
$var_2 = $temp;
}
$var_1 = 'I am var 1';
$var_2 = 'I am var 2';
swap($var_1, $var_2);
echo $var_1 . '<br>';
echo $var_2 . '<br>';
Because a function can only return one value, a swap function couldn't
be written this way unless the variables were passed by reference.