However, if you were to omit this line,
GLOBAL $somevar;
the variable $somevar would be assigned the value 1 because $somevar would then be
considered local within the addit() function. This local declaration would be implicitly
set to 0 and then incremented by 1 to display the value 1.
An alternative method for declaring a variable to be global is to use PHP??™s $GLOBALS
array. Reconsidering the preceding example, you can use this array to declare the
variable $somevar to be global:
CHAPTER 3 ?– PHP BASICS 79
$somevar = 15;
function addit() {
$GLOBALS["somevar"]++;
}
addit();
echo "Somevar is ".$GLOBALS["somevar"];
This returns the following:
Somevar is 16
Regardless of the method you choose to convert a variable to global scope, be
aware that the global scope has long been a cause of grief among programmers due
to unexpected results that may arise from its careless use. Therefore, although global
variables can be extremely useful, be prudent when using them.
Static Variables
The final type of variable scoping to discuss is known as static. In contrast to the variables
declared as function parameters, which are destroyed on the function??™s exit, a
static variable does not lose its value when the function exits and will still hold that
value if the function is called again. You can declare a variable as static simply by
placing the keyword STATIC in front of the variable name:
STATIC $somevar;
Consider an example:
function keep_track() {
STATIC $count = 0;
$count++;
echo $count;
echo "
";
}
keep_track();
keep_track();
keep_track();
80 CHAPTER 3 ?– PHP B ASICS
What would you expect the outcome of this script to be? If the variable $count was
not designated to be static (thus making $count a local variable), the outcome would
be as follows:
1
1
1
However, because $count is static, it retains its previous value each time the function
is executed.
Pages:
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164