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
<?phpfunctiondoubler(&$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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access