Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate number of function calls in the same function

Tags:

php

How to calculate(determine) in php the total number of a function calls but the result of this must be in the same function for which I calculate this number.

Exemple: The test() function is called 100 times(this number is variable and so I don't know it from beginning). I want to find this number in the block of function

test();

function test(){



$no_calls =....
echo $no_calls;  

}

I want the message from echo to be shown only once not to every call of function.

like image 200
Iulian Boiculese Avatar asked Dec 03 '22 06:12

Iulian Boiculese


1 Answers

use a static variable, like this

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

$no_calls will keep its value between calls

In response to your edit, you could do something like this:

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

test();
test();
test();
$final = test();
echo $final;  // will be 4

ok, let's try this a third time:

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

OK, let's try this one more time:

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.

so, we need to magically echo the number of times a function is called: only once, inside the function, without using classes, and 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):

function test() {
  static $no_calls = 1;
  if($no_calls == 1)
  {
    ob_start();
  }
  else
  {
    ++$no_calls;
    ob_clean();
  }
  echo $no_calls;
}

In this instance, when the script terminates, the output buffering left open will automatically flush to the browser.

like image 123
hair raisin Avatar answered Dec 05 '22 19:12

hair raisin