Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Function Parameters

Functions can expect, by declaring them in the function definition, an arbitrary number of arguments. There are two different ways to pass parameters to a function. The first, and more common, is by value. The other is by reference.

Passing Parameters by Value

In most cases, you pass parameters by value. The argument is any valid expression. That expression is evaluated, and the resulting value is assigned to the appropriate variable in the function. In all of the examples so far, we’ve been passing arguments by value.

Passing Parameters by Reference

Passing by reference allows you to override the normal scoping rules and give a function direct access to a variable. To be passed by reference, the argument must be a variable; you indicate that a particular argument of a function will be passed by reference by preceding the variable name in the parameter list with an ampersand (&). Example 3-4 revisits our doubler() function with a slight change.

Example 3-4. Doubler redux
<?php
function doubler(&$value)
{
  $value = $value << 1;
}

$a = 3;
doubler($a);

echo $a;

Because the function’s $value parameter is passed by reference, the actual value of $a, rather than a copy of that value, is modified by the function. Before, we had to return the doubled value, but now we change the caller’s variable to be the doubled value.

Here’s another place where a function contains side effects: since we passed the variable $a into doubler() by reference, the value of $a is at the mercy of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required