When I read the PHP manual, I found the following code:
Copy codeThe Code is as follows:
<? Php
Function Test ()
{
Static $ count = 0;
$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
}
$ Count --;
}
?>
The execution result is as follows:
This is a recursive function. The declared static variable count records the number of times and outputs 1 ~ 10.
When I was reading it, I had a question: static $ count = 0 during recursive calling; the statement will be executed repeatedly. Why does it not cause repeated values to be assigned to the count variable? I studied this question with my colleagues. The code for testing is as follows:
Copy codeThe Code is as follows:
<? Php
Echo 'start <br/> ';
Static $ a = 10;
Echo "$ a <br/> ";
Unset ($ GLOBALS ['a']);
Echo "$ a <br/> ";
Static $ a = 20;
Echo "$ a <br/> ";
$ GLOBALS ['a'] = 10;
Echo "$ a <br/> ";
Static $ a = 30;
Echo "$ a <br/> ";
Unset ($ GLOBALS ['a']);
Echo "$ a <br/> ";
Static $;
Echo "$ a <br/> ";
Static $ a = 40;
Echo "$ a <br/> ";
$ A = 100;
Echo "$ a <br/> ";
Static $ a = 50;
Echo "$ a <br/> ";
Static $ a = 4;
Echo "$ a <br/> ";
Echo 'end <br/> ';
Exit;
?>
The execution result is as follows:
Start
- 4
- Notice: Undefined variable:
- 4
- 10
- 10
- Notice: Undefined variable:
- 10
- 10
- 100
- 100
- 100
- End
(The file location section in the result has been deleted. You can also remove the echo statement and use zend's debug function to view it, so that the result is clearer)
First output of line 1 of code $ The value is 4. It is estimated that PHP will allocate static variable memory during page initialization, at this time, the last declared value of the same variable is used (this can change 4 to another number test ). Line 3 of the Code calls the unset function to destroy the variable $ a. when the value of $ a is output again, the undefined variable prompt is displayed, indicating that the variable has been destroyed.
When the second row is output again, the output result is still 4 rather than 20. There are two possibilities. One is that php initializes the value of $ a again, another is that php uses the value before $ a is destroyed. This problem is solved when the 20th rows are output. When row 16th $ a is destroyed, the value is 10, and after row 19th is declared, the output is still 10.
In row 11th, the value of $ a is changed to 10, and $ a is declared again in row 14, and the output of Row 17 is considered as 10. It is assumed that php still uses the value in the memory of the static variable during the repeat, without assigning a value again.
So far, the problems found in the manual have been solved, that is, the declaration in the recursive call does not change the value of $ count, so the recursion stops successfully when $ count = 10.
You may not be able to understand it correctly.