国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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.


Continuing Learning
||
<?php //--------------如何理解static靜態(tài)變量----------- /** 普通局部變量 */ function local() { $loc = 0; //這樣,如果直接不給初值0是錯誤的。 ++$loc; echo $loc . '<br>'; } local(); //1 local(); //1 local(); //1 echo '===================================<br/>'; /** static靜態(tài)局部變量 */ function static_local() { static $local = 0 ; //此處可以不賦0值 $local++; echo $local . '<br>'; } static_local(); //1 static_local(); //2 static_local(); //3 //echo $local; 注意雖然靜態(tài)變量,但是它仍然是局部的,在外不能直接訪問的。 echo '=======================================<br>'; /** static靜態(tài)全局變量(實際上:全局變量本身就是靜態(tài)存儲方式,所有的全局變量都是靜態(tài)變量) */ function static_global() { global $glo; //此處,可以不賦值0,當然賦值0,后每次調(diào)用時其值都為0,每次調(diào)用函數(shù)得到的值都會是1,但是不能想當然的寫上"static"加以修飾,那樣是錯誤的. $glo++; echo $glo . '<br>'; } static_global(); //1 static_global(); //2 static_global(); //3 ?>
submitReset Code