Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>use a <a href="http://us2.php.net/manual/en/language.variables.scope.php#language.variables.scope.static" rel="noreferrer">static</a> variable, like this</p> <pre><code>function test(){ static $no_calls = 0; ... ++$no_calls; } </code></pre> <p>$no_calls will keep its value between calls</p> <p>In response to your edit, you could do something like this:</p> <pre><code>function test() { static $no_calls = 0; ++$no_calls; ... return $no_calls; } test(); test(); test(); $final = test(); echo $final; // will be 4 </code></pre> <p>ok, let's try this a third time:</p> <pre><code>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 </code></pre> <p>OK, let's try this one more time:</p> <pre><code>class Test { private $no_calls; function test() { ... ++$this-&gt;no_calls; } function __destruct() { echo $this-&gt;no_calls; } } $test = new Test(); $test-&gt;test(); $test-&gt;test(); $test-&gt;test(); $test-&gt;test(); //when $test falls out of scope, 4 will be echoed. </code></pre> <p>so, we need to magically echo the number of times a function is called: only once, inside the function, without using classes, <em>and</em> without telling the function that it is the last call. Hold on to your hats (warning, I do not suggest using this code for many reasons (but you leave me no choice), and it WILL NOT work if there is to be any output in between function calls, including by the function itself):</p> <pre><code>function test() { static $no_calls = 1; if($no_calls == 1) { ob_start(); } else { ++$no_calls; ob_clean(); } echo $no_calls; } </code></pre> <p>In this instance, when the script terminates, the output buffering left open will automatically flush to the browser.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload