[Previous] [Contents] [Next]

How Variables Are Passed to Functions

By default, variables are passed to functions by value, not by reference. The following example:

function doublevalue($var)
{
  $var = $var * 2;
}
$variable = 5;
doublevalue($variable);
echo "\$variable is: $variable";

has the output:

$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 be 10, and the result lost forever! The value is passed to the function, not the variable itself.

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]