Looking at the PHP manual, I found the following code:
Copy the Code code as follows:
function Test ()
{
static $count = 0;
$count + +;
Echo $count;
if ($count < 10) {
Test ();
}
$count--;
}
?>
The results of the implementation are as follows:
This is a recursive function that declares the number of static variables count records, output 1~10.
I have a doubt when I look at it, when the recursive call static $count = 0; Statement executes repeatedly, why doesn't it cause the count variable to be assigned repeatedly? With this question and colleague research, the test code is as follows:
Copy the Code code as follows:
Echo ' Start
';
static $a = 10;
echo "$a
";
unset ($GLOBALS [' a ']);
echo "$a
";
static $a = 20;
echo "$a
";
$GLOBALS [' a '] = 10;
echo "$a
";
static $a = 30;
echo "$a
";
unset ($GLOBALS [' a ']);
echo "$a
";
static $a;
echo "$a
";
static $a = 40;
echo "$a
";
$a = 100;
echo "$a
";
static $a = 50;
echo "$a
";
static $a = 4;
echo "$a
";
Echo ' End
';
Exit
?>
The results of the implementation are as follows:
Start
- 4
- notice:undefined variable:a
- 4
- 10
- 10
- notice:undefined variable:a
- 10
- 10
- 100
- 100
- 100
- End
(the part of the result about the location of the file has been deleted.) You can also remove the Echo statement using Zend's debug function to see the results clearer)
code line 5th first output $a has a value of 4, presumably PHP allocates static variable memory when the page is initialized, using the value of the last declaration of the same variable (this can change 4 to another number test). The code line 7th calls the unset function to destroy the variable $ A, and when you output $ A again, you see a hint that the variable is not defined, stating that the variable has been destroyed.
Line 10th again output, the output is still 4 instead of 20, there are two possible, one is PHP again initialized $ A value, and the other is PHP uses a $ A before the destruction of the value, this problem is resolved on the 20th line output. A value of 10 is destroyed in line 16th and the output is still 10 after the 19th row is declared.
The value of $ A is modified to 10 in line 11th, and the $a,17 row output is declared to be 10 in 14 rows. It is assumed that PHP uses static variable values in memory instead of assigning values again when repeating declarations.
At this point, the problem found in the manual has largely been resolved, that is, the declaration in the recursive call did not change the value of the $count, so the recursion was stopped successfully at $count=10.
There may be an incorrect understanding of the place, welcome to shoot bricks.
The above introduces the study and analysis of the principle of static keyword in the Star Alliance PHP, including the content of Star Alliance, hoping to be helpful to a friend who is interested in PHP tutorial.