亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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是錯(cuò)誤的。 ++$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)變量,但是它仍然是局部的,在外不能直接訪(fǎng)問(wèn)的。 echo '=======================================<br>'; /** static靜態(tài)全局變量(實(shí)際上:全局變量本身就是靜態(tài)存儲(chǔ)方式,所有的全局變量都是靜態(tài)變量) */ function static_global() { global $glo; //此處,可以不賦值0,當(dāng)然賦值0,后每次調(diào)用時(shí)其值都為0,每次調(diào)用函數(shù)得到的值都會(huì)是1,但是不能想當(dāng)然的寫(xiě)上"static"加以修飾,那樣是錯(cuò)誤的. $glo++; echo $glo . '<br>'; } static_global(); //1 static_global(); //2 static_global(); //3 ?>
submitReset Code