PHP Variables Static
PHP static variable is used to remember the value of a local variable when we call the function in our program. While your script is running a static variable is only retained by the function , but it is NOT shared with the main code.
The crucial fact is that PHP function does not have the ability to remember the value of a local variable that has been created within the function. The entire knowledge of the value of the function's variable disappears, Once the function is finished.
To solve this problem we use PHP static statement that tells the function to remember the location of the local variable when we call the function
Let's see the example below :
static $text = 0;
$month = array("December","January","February","March","April","May","June","July","August","September","October","November");
$text %= count($month);
for($i=0; $i<12; $i++)
print "How many months in a year - ".months()."<br />";
Here, in this example we declared the $text variable twice in the program. The first time we declared outside the function and the second declared within the function. If you noticed, we mentioned static statement before the $text variable within the function to remembered the value of the local variable.
In this line, we make an array of months and increases the current value of the $text variable by 1.
At the end, we used for loop to display the different month name everytime.
Posted on: January 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles