Take a look at the example below:
Copy code The code is as follows:
function Test()
{
$w3sky = 0;
echo $w3sky;
$w3sky++;
}
? >
Every time this function is called, it will 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 the code The code is as follows:
function Test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
Every time Test() is called, this function 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;
}
?>
The above introduces the detailed explanation of the use of static variables in st patrick day php, including the content of st patrick day. I hope it will be helpful to friends who are interested in PHP tutorials.