This is commonly referred to as a variable reference. Changes made to referenced
variables change the original.
To demonstrate this idea, imagine we wanted a function that stripped commas from
numbers. That way if we got something like "10,000" from an input field we would know
it was ten thousand, not ten. We could build the function by passing a string and returning
it with the commas removed. But in this case we want to just pass the variable and have it
be changed. Listing 4.3 demonstrates this functionality.
It is also possible to make an argument optional. Many built-in functions provide this
functionality. The date function is one you should be familiar with by now. You can pass
one or two arguments to date. The first argument is the format of the return value. The
second argument is the timestamp, a date expressed in seconds since January 1, 1970. If
the second argument is omitted, the current time is used.
You do this in your own functions by providing a default value using the = operator
immediately after the argument. The right side of = is a literal value that the variable will
be assigned. See Listing 4.4. Since arguments are matched up left to right, you must
provide a default value for every argument after the first with a default value.
Listing 4.3 Passing Arguments by Reference
<?
function stripCommas(&$inputString)
{
$inputString = ereg_replace(",", "", $inputString);
}
$myNumber = "10,000";
stripCommas($myNumber);
print($myNumber);
?>
You may set an argument to be unset by default by making it equal to NULL, a special
constant. Listing 4.5 demonstrates this functionality.
Other than named arguments, you may also access arguments by their position using
three functions, func_get_arg, func_getargs, func num_args. These functions
are described in Chapter 8. You may either fetch one argument at a time using
func_get_arg, or fetch them all as an array using func_get_args. To find out how
many arguments were passed, use func_num_args. There is an implication lurking here.
Calling a function with a number of arguments different from the prototype is not an
error unless you write your function that way.
Listing 4.4 Arguments with Default Values
<?
function printColored($Text, $Color="black")
{