计算同一函数中的函数调用数

Iul*_*ese 2 php

如何在php中计算(确定)函数调用的总数,但其结果必须与我计算此数字的函数相同.

例子:test()函数被调用100次(这个数字是可变的,因此我从一开始就不知道它).我想在功能块中找到这个数字

test();

function test(){



$no_calls =....
echo $no_calls;  

}
Run Code Online (Sandbox Code Playgroud)

我希望echo中的消息只显示一次,而不是每次调用函数.

hai*_*sin 8

使用静态变量,像这样

function test(){
  static $no_calls = 0;
  ...
  ++$no_calls;
}
Run Code Online (Sandbox Code Playgroud)

$ no_calls将在调用之间保持其值

为了响应您的编辑,您可以执行以下操作:

function test() {
  static $no_calls = 0;
  ++$no_calls;
  ...
  return $no_calls;
}

test();
test();
test();
$final = test();
echo $final;  // will be 4
Run Code Online (Sandbox Code Playgroud)

好吧,让我们第三次尝试:

function test($last_time = false) {
  static $no_calls = 0;
  ++$no_calls;
  ...
  if($last_time)
  {
    echo $no_calls;
  }
}

test();
test();
test();
test(true);  // will echo 4
Run Code Online (Sandbox Code Playgroud)

好的,让我们再试一次:

class Test {
  private $no_calls;
  function test()
  {
    ...
    ++$this->no_calls;
  }
  function __destruct()
  {
    echo $this->no_calls;
  }
}

$test = new Test();
$test->test();
$test->test();
$test->test();
$test->test();
//when $test falls out of scope, 4 will be echoed.
Run Code Online (Sandbox Code Playgroud)

因此,我们需要神奇地回显调用函数的次数:在函数内部只调用一次,而不使用类,并且不告诉函数它是最后一次调用.坚持你的帽子(警告,我不建议使用这个代码有很多原因(但你别无选择),如果函数调用之间有任何输出,包括函数本身,它将无法工作) :

function test() {
  static $no_calls = 1;
  if($no_calls == 1)
  {
    ob_start();
  }
  else
  {
    ++$no_calls;
    ob_clean();
  }
  echo $no_calls;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当脚本终止时,打开的输出缓冲将自动刷新到浏览器.