4.4. Static Variables

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 to 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 statement.

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 ...

Get Core PHP Programming, Third Edition 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.