PHP static static variable use method
- 2020-03-31 20:47:37
- OfStack
Take a look at the following example:
This function sets the value of $w3sky to 0 and prints "0" each time it is called. Adding a variable to $w3sky++ does not work because the variable $w3sky does not exist once the function exits. To write a counting function that will not lose the count value, define the variable $w3sky as static:
As follows:
This function prints the value of $w3sky and adds one for each call to Test().
Static variables also provide a way to handle recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, because they can go on forever without an exit. Make sure you have a way to stop the recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Examples of static variables and recursive functions:
Note: static variables can be declared as in the above example. Assigning the result of an expression to it in a declaration results in a parsing error.
Example of declaring static variables:
<?php
function Test()
{
$w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
This function sets the value of $w3sky to 0 and prints "0" each time it is called. Adding a variable to $w3sky++ does not work because the variable $w3sky does not exist once the function exits. To write a counting function that will not lose the count value, define the variable $w3sky as static:
As follows:
<?php
function Test()
{
static $w3sky = 0;
echo $w3sky;
$w3sky++;
}
?>
This function prints the value of $w3sky and adds one for each call to Test().
Static variables also provide a way to handle recursive functions. A recursive function is a method that calls itself. Be careful when writing recursive functions, because they can go on forever without an exit. Make sure you have a way to stop the recursion. The following simple function recursively counts to 10, using the static variable $count to determine when to stop:
Examples of static variables and recursive functions:
<?PHP
function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test();
}
$count--;
}
?>
Note: static variables can be declared as in the above example. Assigning the result of an expression to it in a declaration results in a parsing error.
Example of declaring static variables:
<?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;
}
?>