1

I was learning php declare statement.I sow the following php code:

<?php

declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
    echo "<br>tick_handler() called ";
}

register_tick_function('tick_handler');

$a = 1;
if ($a > 0) {
    $a += 2;
    print($a);   
}

?>

The output:

tick_handler() called
tick_handler() called
tick_handler() called 3
tick_handler() called 

I can't understand why "tick_handler() called" is printing 4 times and why " tick_handler() called 3" appears at 3rd print.please help me with simple explanation.thanks

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
user5005768Himadree
  • 1,375
  • 3
  • 23
  • 61
  • If you look to the second example then you will get the clear picture:- http://php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks – Alive to die - Anant Jan 25 '17 at 06:37

1 Answers1

1

Actually your are confused because of your code structure.It need to be linke below:-

<?php

declare(ticks=1); //this is a tick so tick_handler() will call and first time it outputs
// A function called on each tick event
function tick_handler()
{
    echo "tick_handler() called ";
    echo PHP_EOL;
}

register_tick_function('tick_handler');

$a = 1; // this a tick so again tick_handler() will call and second times output
if ($a > 0) {
    $a += 2; // this is a tick so again tick_handler() will call and third times output
    print($a);//  it prints first the $a  and because its a tick again so tick_handler() will call and fourth times output
}

?>

output:-https://eval.in/723678

Note:- A more clear picture will be found in the second example of the link:- http://php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98