Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

explicitly tell PHP you want a global variable to be present in the function. Listing 2.2
uses the metaphor of the United States to demonstrate.


The script sets up a function, printCity, that prints out the name of a city. It will be used
to show the contents of the variables named capital. Variables is plural because there
are actually three variables in the script named capital. One is global and the other two
are local to the California and Utah functions.


When you run this script you will find that the cities are printed in the order Washington
DC, Sacramento, Salt Lake City, and Washington DC. Notice that even though we have
given capital a new value inside California, it is not the same variable we set to
Washington DC. The variables inside California and Utah exist within their own space
and are created and destroyed each time the functions are called.


It is important to remember that when you create a variable inside a function, it exists
only while that function is executing. Once execution finishes and control is passed back
the calling process, all the variable space for that function is cleaned up. Sometimes this
is not desirable; sometimes you want the function to remember the values of the variables
between calls. You could implement this by using global variables, but a more elegant
solution is to use the static command.


At the beginning of a function, before any other commands, you may declare a static
variable. The variable will then retain any value it holds, even after leaving the function.
You might wonder why you would ever need to do this. Suppose you'd like to build a
table where the rows alternate in background color. Listing 2.3 does just this.


Listing 2.3 Demonstrations of Static Variables

Free download pdf