Take a look at the following example:
Copy code The code is as follows:
function Test()
{
$w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
Every time this function is called Set the value of $w3sky to 0 and output "0". Increasing the variable $w3sky++ by one has no effect, because the variable $w3sky does not exist once this function exits. To write a counting function that will not lose this count value, define the variable $w3sky as static:
as follows:
Copy code The code is as follows:
function Test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++ ;
}
?>
Every time this function calls Test(), it will output the value of $w3sky and increment it by one.
Static variables also provide a way to deal with recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely without an exit. Be sure to have a way to abort the recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Example of static variables and recursive functions:
Copy code The code is as follows:
function Test()
{
static $count = 0;
$count++;
echo $count ;
if ($count < 10) {
Test();
}
$count--;
}
?>
Note: Static variables can be declared as shown in the above example. Assigning it with the result of an expression in a declaration will result in a parsing error.
Example of declaring static variables:
Copy code The code is as follows:
function foo( ){
static $int = 0;// correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>
http://www.bkjia.com/PHPjc/321999.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321999.htmlTechArticleLook at the following example: Copy the code The code is as follows: ?php function Test() { $w3sky = 0; echo $w3sky; $w3sky++; } ? Each time this function is called, it will set the value of $w3sky to 0 and output "...