Static variables in PHP
Archive - Originally posted on "The Horse's Mouth" - 2007-10-05 07:46:07 - Graham EllisWhen you call a function, you typically want a nice clean start with no "leftovers" from the previous call. And that's what you get by default in PHP. However, there can be exceptions where you want data to be retained and you can do that using:
EITHER a global variable which is shared with the main PHP script and retained throughout its run
OR a static variable which is retained by the function while your script is running, but is NOT shared with the main code.
The typical use of a static variable is in what we call an iterator - a function which steps through a series of results, generating the next value in the sequence each time it's called. Here is a code example:
<?php
$walrus = 77;
function nextmeal () {
static $walrus = 0;
$munch = array("fish","seagull","penguin","ice");
$walrus++;
$walrus %= count($munch);
return $munch[$walrus];
}
for ($k=0; $k<10; $k++) {
print "What's for dinner - ".nextmeal()."?<br />";
}
print $walrus; # Just to show you this is a different walrus!
?>
And here are the results:
What's for dinner - seagull?
What's for dinner - penguin?
What's for dinner - ice?
What's for dinner - fish?
What's for dinner - seagull?
What's for dinner - penguin?
What's for dinner - ice?
What's for dinner - fish?
What's for dinner - seagull?
What's for dinner - penguin?
77
You'll note that our Walrus gets a different meal each day, because the static variable $walrus within the nextmeal function is retained. But (just as a demonstration) the $walrus variable in the main code is set to 77 and remains at that value.
Full source code here and run it here. Further example [here]. Learn about it on a course run here.