Page 89 - Open Soource Technologies 304.indd
P. 89
Unit 4: Functions
Notes
// Function with STATIC variable
function f_static() {
STATIC $x = 0;
echo ‘<br /> x = ‘. $x;
$x++;
}
// Calling the f_local() function
f_local(); // 0
f_local(); // 0
f_local(); // 0
echo ‘<hr />’;
// Caling the f_static() function
f_static(); // 0
f_static(); // 1
f_static(); // 2
?>
Every time the f_local() function is called it sets $x to 0 and prints 0. The $x++ which increments the
variable serves no purpose since as soon as the function exits the value of $x variable disappears.
In the f_static() function, $x is initialized only in first call of function and every time the f_static()
is called, it will remember the value of $x, and will print and increment it. This code will output:
x = 0
x = 0
x = 0
x = 0
x = 1
x = 2
Develop a PHP program to differentiate between global and static variable
declaration.
4.4 Function Parameters
There are two different ways of passing these arguments. The first is the most common, which is
called passing by value, and the second is called passing by reference. Which kind of argument
passing you would like is specified in the function definition itself and not during the function call.
LOVELY PROFESSIONAL UNIVERSITY 83