Search code examples
phpdeclare

PHP misunderstanding number of tickable statements using PHP ticks?


I know what ticks are in PHP, but looking at the output of the following code:

<?php

function myfunc() {
    static $n = 1;
    print "$n) Tick<br>";
    $n++;
}

register_tick_function("myfunc");

declare(ticks=1);
    echo 'echo<br>';

The output is:

1) Tick
2) Tick
echo
3) Tick

It tells me that the registered tick function 'myfunc' is executed 3 times. But, based on this answer -> PHP using Declare ? What is a tick?:

You get a tick for each line ; and each block {}

Shouldn't it be:

1) Tick
echo
2) Tick

? As there are only two statements:

declare(ticks=1);<-- Statement 1
        echo 'echo<br>';<-- Statement 2

Why 3??? If I remove the ";" from declare, like this:

declare(ticks=1)
        echo 'echo<br>';

I get the only one execution of the registered tick function:

echo
1) Tick

So what is the definitely rule to count the tickable statements in order to understand how many times a registered tick function is executed? (I am asking it because of this example and because PHP manual actually doesn't cover the topic on counting tickable stats)

EDIT: Another strange behaviour in my opinion is this:

<?php

function myfunc()
{
    static $n = 1;
    print "$n) Tick<br>";
    $n++;
}

register_tick_function("myfunc");
declare(ticks = 1)
    echo 'Start<br>';
    echo 'echo<br>';

which outputs:

Start
1) Tick
echo

The tick function is executed once, but the statements are at least 2 (if not counting the "end of the script" as @Marc B has pointed out)


Solution

  • what I finelly found is:

    function myfunc()
        {
            static $n = 1;
            print "$n) Tick<br>";
            $n++;
        }
    
        register_tick_function("myfunc");
        declare(ticks = 1) {
    
        //echo 'Start<br>';
        echo 'echo<br>';
    
        }
    

    outputs 2 ticks, one for block {} and 1 for echo. if you uncomment 'Start' that will bring 1 more tick as you expected.

    So I think the best practice is to always use

    declare(ticks=1) { } 
    

    with block brackets