[Previous] [Contents] [Next]


Passing arguments by reference

An alternative to returning a result or using a global variable is to pass a reference to a variable as an argument to the function. This means that any changes to the variable within the function affect the original variable. Consider this example:

function doublevalue(&$var)
{
  $var = $var * 2;
}

  $variable = 5;
  doublevalue($variable);
  echo "\$variable is: $variable";
?>

This 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.

Functions that are defined with arguments that are references to variables can't be called with literal expressions, because the function expects a variable to modify. PHP reports an error when such a call is made.


[Previous] [Contents] [Next]