GerBawn
GerBawn

Reputation: 301

How declare structure work in php

The code:

declare(ticks=1);

function tick_handler(){
    echo "tick_handler() called\n";
}

register_tick_function('tick_handler');
$a = 1;
if($a < 2){
    // $a += 2;
}

When I run this code, it will print tick_handler() called four times.I think $a = 1 will print tick_handler() called one times, but why it print four times. If I change first line of code:

declare(ticks = 2)

it will print same result like before. In php document, it said:

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block

So I think if ticks = 2, it will print two times, but it doesn't. Now, I do not know how it works。

Upvotes: 1

Views: 68

Answers (1)

Amarnasan
Amarnasan

Reputation: 15529

Consider running this code, incrementing the ticks and running again, from 1 to 10 (more or less), then maybe you'll get how does it works.

declare(ticks=1);
function tick_handler(){
    echo "tick_handler() called<br>";
}
echo("1<br>");
register_tick_function('tick_handler');
echo("2<br>");
$a = 1;
echo("3<br>");
if($a < 2){
    echo("4<br>");
    // $a += 2;
}
echo("5<br>");

I would explain it as: every N "ticks" (which may be an esoteric way PHP has to measure its inner instructions to run a single high level call (like a print)) call this function. You cannot make the equivalence 2 tick => one instruction, 1 ticks => two instructions.

The "issue" with your code is that you set the ticks number BEFORE registering the tick handler, and then one call is missed because the function has not been registered. Actually, the call is issued DURING THE REGISTRATION of the tick handler. If you start counting ticks after the declaration

function tick_handler(){
    echo "tick_handler() called<br>";
}

register_tick_function('tick_handler');
declare(ticks=1);  //2..3...etc..

$a = 1;
if($a < 2){
    // $a += 2;
}

then the different results with different values for ticks are more coherent.

Upvotes: 1

Related Questions