Home Tutorial Php PHP Variables Static

 
 

Share on Google+Share on Google+
PHP Variables Static
Posted on: January 15, 2010 at 12:00 AM
Advertisement
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.

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 :

<?php

$text = 100;

function months ()

{

static $text = 0;

$month = array("December","January","February","March","April","May","June","July","August","September","October","November");

$text++;

$text %= count($month);

return $month[$text];

}

for ($i=0; $i<12; $i++)

 {

print "How many months in a year - ".months()."<br />";

}

print $text;

?>

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.

Advertisement

Related Tags for PHP Variables Static:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 15, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com