search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

首页课程PHP Fun Breakthrough ClassStatic variables of custom functions

Static variables of custom functions

目录列表

静态变量

如果我想知道函数被调用了多少次怎么办?在没有学习静态变量的时候,我们没有好的办法来解决。

静态变量的特点是:声明一个静态变量,第二次调用函数的时候,静态变量不会再初始化变量,会在原值的基础上读取执行。

有了这个特点,我们就可以实现,最开始我们的提问:

函数调用次数如何统计?

先执行10次demo()函数试试,再执行10次test()函数试试:

<?php
function demo()
{
   $a = 0;
   echo $a.'<br>';
   $a++;
}
function test()
{
   static $a = 0;
   echo $a.'<br>';
   $a++;
}
demo();
demo();

test();
test();

?>

上例中你会发现:

  • test();执行一次数值就会加1,而demo输出的显示结果,始终为0。

  • 通过上例你就会发现,本文开始处说明的静态变量的特点。

将下列排序修改正确。

  • static $a = 0;
  • }
  • function test() {
  • $a++;
  • echo $a;
1/2