PHP - static declaration
Archive - Originally posted on "The Horse's Mouth" - 2007-01-04 08:15:20 - Graham EllisIf you want to retain the value of a variable between one call to a function and the next, you can declare it as static. And as part of the initial declaration, you can assign a starting value to it. This allows you to test whether you're calling a function for the first time, or for a subsequent time.
function getavail($stamp,$forevent = 0) {
static $haverooms = 0;
static $blocked, $held;
if (! $haverooms) {
$haverooms = 1;
$blocked = array();
$held = array();
etc
OK - so that's the feature - so what's the benefit?
Using a static in this way allows you to include code to initialise variables AND make use of them in the same logical block - making maintainance of code much easier than in would be if you were passing parameters around, or relying on globals.
A block of code that runs only the first time a function is called is also useful if the function is required to do some heavy work that doesn't change within a running of your program; there's no point in re-calculating a value that you had already calculated, but lost when you exited from a function, is there? The code snippet above is a good example of this - over the New Year, I've been updating our online booking system to include hotel rooms as well as courses, and to dynamically refer back to the databases as it offers available rooms and courses to web site visitors. My getavail function returns the number of (rooms) available on a certain date, passed in by the time stamp variable. The workings are quite intricate at times, and when we produce a calendar of availability we have to keep calling it for day after day .... so we seed the $blocked and $held arrays during the first call - pre-loading tables of events, courses, prior bookings and closure periods which aren't going to change within the few milliseconds the program takes to run.
Are statics always useful? No - they are fiercely anti-OO. In other words, I would have a major problem if I wanted to extend my events tables, etc, to cover two different hotel objects. Ah - but I don't see us opening a second hotel in the near future.
((See further example - global / static / regular - [here]))