Page 90 - Open Soource Technologies 304.indd
P. 90
Web Technologies-I
Notes 4.4.1 By-Value Parameters
Here, the argument can be any valid expression, the expression is evaluated, and its value is
assigned to the corresponding variable in the function. For example, here, $x is assigned the value
8 and $y is assigned the value of $c:
Function pow($x, $y)
{
...
}
pow(2*4, $c);
4.4.2 By-Reference Parameters
Passing by-reference requires the argument to be a variable. Instead of the variable’s value being
passed, the corresponding variable in the function directly refers to the passed variable whenever
used. Thus, if you change it inside the function, it affects the sent variable in the outer scope as well:
function square(&$n)
{
$n = $n*$n;
}
$number = 4;
square($number);
print $number;
The & sign that precedes $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.
4.4.3 Default Parameters
Default parameters like C++ are supported by PHP. Default parameters enable you to specify a
default value for function parameters that are not passed to the function during the function call.
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.
84 LOVELY PROFESSIONAL UNIVERSITY