Another important feature of the range of variables in php is static variables ). Static variables exist only in the local function domain and are initialized only once. When the execution of a program leaves this scope, the value of the static variables will not disappear and the result of the last execution will be used.
Another important feature of the range of variables in php is static variables ). Static variables exist only in the local function domain and are initialized only once. When the execution of a program leaves this scope, the value of the static variables will not disappear and the result of the last execution will be used.
Take a look at the following example:
The Code is as follows:
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:
The Code is as follows:
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:
The Code is as follows:
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:
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;
}
?>