Page 111 - Open Soource Technologies 304.indd
P. 111
Open Source Technologies
Notes The following example function accepts one argument, $x, and returns its square:
Example: function square ($x)
{
return $x*$x;
}
After defining this function, it can be used as an expression wherever you desire.
For example:
print ‘The square of 5 is ‘ . square(5);
7.2 Function Scope
Every function has its own set of variables. Any variables used outside the function’s definition
are not accessible from within the function by default. When a function starts, its function
parameters are defined. When you use new variables inside a function, they are defined within
the function only and don’t hang around after the function call ends. In the following example,
the Variable $var is not changed by the function call:
Example: function func ( )
{
svar = 2;
}
$var = 1;
func( );
print $var;
When the function func is called, the variable $var, which is assigned 2, is only in the scope of
the function and thus does not change $var outside the function. The code snippet prints out 1.
Now hat if you actually do want to access and/or change $var on the outside? As mentioned
in the “Variables” section, you can use the built-in $ GLOBALS[] array to access variables in
the global scope of the script
Rewrite the previous script the following way:
Function func ()
{
$ GLOBALS[“var”] = 2;
}
$var = 1;
func ( );
print $var;
It prints the value 2.
106 LOVELY PROFESSIONAL UNIVERSITY