Static variables of php custom functions
What if I want to know how many times a function has been called? Without learning static variables, we have no good way to solve it.
The characteristics of static variables are: declare a static variable, and when the function is called for the second time, the static variable will not initialize the variable again, but will read and execute based on the original value.
With this feature, we can realize our first question:
Statistics of the number of function call words.
First try executing the demo() function 10 times, and then try executing the test() function 10 times:
<?php function demo() { $a = 0; echo $a; $a++; } function test() { static $a = 0; echo $a; $a++; } demo(); demo(); demo(); demo(); demo(); demo(); demo(); demo(); demo(); demo(); /* for($i = 0 ;$i < 10 ; $i++){ test(); } */ ?>
In the above example, you will find:
test(); execution The value will be incremented by 1 once, and the displayed result of the demo output is always 0.
Through the above example, you will find the characteristics of static variables explained at the beginning of this article.