Take a look at the following example:
CopyCode The Code is as follows: <? PHP
Function Test ()
{
$ W3sky = 0;
Echo $ w3sky;
$ W3sky ++;
}
?>
This function sets $ w3sky to 0 and outputs "0" for each call ". Adding $ w3sky ++ to the variable has no effect, because the variable $ w3sky does not exist once the function is exited. To write a counting function that does not lose the current Count value, you must define the variable $ w3sky as static:
As follows:Copy codeThe Code is as follows: <? PHP
Function Test ()
{
Static $ w3sky = 0;
Echo $ w3sky;
$ W3sky ++;
}
?>
Every time test () is called, this function outputs the value of $ w3sky and adds one.
Static variables also provide a method for processing recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, because infinite recursion may occur without exit. Make sure there are methods to stop recursion. The following simple function recursively counts to 10 and uses the static variable $ count to determine when to stop:
Example of static variables and recursive functions:Copy codeThe Code is as follows: <? PHP
Function Test ()
{
Static $ COUNT = 0;
$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>
Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.
Example of declaring static variables:Copy codeThe Code is as follows: <? PHP
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;
}
?>