That is, it can be referenced only in
that function. Any assignment outside of that function will be considered to be an
entirely different variable from the one contained in the function. Note that when
you exit the function in which a local variable has been declared, that variable and its
corresponding value are destroyed.
Local variables are helpful because they eliminate the possibility of unexpected
side effects, which can result from globally accessible variables that are modified,
intentionally or not. Consider this listing:
CHAPTER 3 ?– PHP BASICS 77
$x = 4;
function assignx () {
$x = 0;
printf("\$x inside function is %d
", $x);
}
assignx();
printf("\$x outside of function is %d
", $x);
Executing this listing results in the following:
$x inside function is 0
$x outside of function is 4
As you can see, two different values for $x are output. This is because the $x located
inside the assignx() function is local. Modifying the value of the local $x has no bearing
on any values located outside of the function. On the same note, modifying the $x
located outside of the function has no bearing on any variables contained in assignx().
Function Parameters
As in many other programming languages, in PHP, any function that accepts arguments
must declare those arguments in the function header. Although those arguments
accept values that come from outside of the function, they are no longer accessible
once the function has exited.
Pages:
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162