Saving State Between Function Calls with the static Statement

Variables within functions have a short but happy life on the whole. They come into being when the function is called and die when execution is finished, as they should. It is usually best to build a script as a series of self-contained blocks, each with as little knowledge of others as possible. Occasionally, however, you may want to give a function a rudimentary memory.

Let's assume that we want a function to keep track of the number of times it has been called so that numbered headings can be created by a script. We could, of course, use the global statement to do this, as shown in Listing 6.8.

Listing 6.8. Using the global Statement to Remember the Value of a Variable Between Function ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.