Tripod5G > Variable scope
3pod PHP Learning
Variable scope
The scope of a variable is the context within which it is defined. For the most part all PHP variables only
have a single scope. However, within user-defined functions a local function scope is introduced. Any
variable used inside a function is by default limited to the local function scope. For example:
$a = 1; /* global scope */
Function Test () {
echo $a; /* reference to local scope variable */
}
Test ();
This script will not produce any output because the echo statement refers to a local version of the $a
variable, and it has not been assigned a value within this scope. You may notice that this is a little bit
different from the C language in that global variables in C are automatically available to functions unless
specifically overridden by a local definition. This can cause some problems in that people may
inadvertently change a global variable. In PHP global variables must be declared global inside a function
if they are going to be used in that function. An example:
$a = 1;
$b = 2;
Function Sum () {
global $a, $b;
$b = $a + $b;
}
Sum ();
echo $b;
The above script will output "3". By declaring $a and $b global within the function, all references to
either variable will refer to the global version. There is no limit to the number of global variables that can
be manipulated by a function.
86

Next >>
bluedot bluedots greydots pinkdots

Tripod >> 3pod Tips & Learning and manuals for educations