Page 114 - Open Soource Technologies 304.indd
P. 114
Unit 7: Functions
whenever used. Thus, if you change it inside the function, it affects the sent variable in the Notes
outer scope as well:
Example: function square(&$n)
{
$n = $n*$n;
}
$number = 4;
square($number);
print $number;
The & sign that proceeds $n in the function parameters tells PHP to pass it by-reference, and
the result of the function call is $number squared; thus, this code would print 16.
7.6 Default Parameters
Default parameters like C++ are supported by PHP. Default P( )arameters enable you to specify
a default value for function parameters that aren’t passed to the function during the function
call. The default values you specify must be a constant value, such as a scalar, array with scalar
values, or constant.
The following is an example for using default parameters:
Example: function increment(&$num, $increment = 1)
{
$num += $increment;
}
$num = 4;
increment($num);
increment($num, 3);
This code results in $num being incremented to 8. First, it is incremented by 1 by the first call
to increment, where the default increment size of 1 is used, and second, it is incremented by
3, altogether by 4.
When you a call a function with default arguments, after you omit a default
function argument, you must emit any following arguments. This also means
that following a default argument in the function’s definition, all other
arguments must also be declared as default arguments.
7.7 Static Variables
Like C, PHP supports declaring local function variables as static. These kind of variables remain
in tact in between function calls, but are still only accessible from within the function they are
declared. Static variables can be initialized, and this initialization only takes place the first time
the static declaration is reached.
LOVELY PROFESSIONAL UNIVERSITY 109