3pod PHP Learning |
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as: $a = 1; $b = 2; Function Sum () { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum (); echo $b; The $GLOBALS array is an associative array with the name (exp 3pod.com) of the global variable being the key and the contents of that variable being the value of the array element. Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: Function Test () { $a = 0; echo $a; $a++; } This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static: Function Test () { static $a = 0; echo $a; $a++; } Now, every time the Test() function is called it will print the value of $a and increment it. Static variables are also essential when functions are called recursively. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it 87 |
Next >> |
Tripod >> 3pod Tips & Learning and manuals for educations