Static variable...LOGIN

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.


Next Section
<?php //--------------如何理解static静态变量----------- /** 普通局部变量 */ function local() { $loc = 0; //这样,如果直接不给初值0是错误的。 ++$loc; echo $loc . '<br>'; } local(); //1 local(); //1 local(); //1 echo '===================================<br/>'; /** static静态局部变量 */ function static_local() { static $local = 0 ; //此处可以不赋0值 $local++; echo $local . '<br>'; } static_local(); //1 static_local(); //2 static_local(); //3 //echo $local; 注意虽然静态变量,但是它仍然是局部的,在外不能直接访问的。 echo '=======================================<br>'; /** static静态全局变量(实际上:全局变量本身就是静态存储方式,所有的全局变量都是静态变量) */ function static_global() { global $glo; //此处,可以不赋值0,当然赋值0,后每次调用时其值都为0,每次调用函数得到的值都会是1,但是不能想当然的写上"static"加以修饰,那样是错误的. $glo++; echo $glo . '<br>'; } static_global(); //1 static_global(); //2 static_global(); //3 ?>
submitReset Code
ChapterCourseware