PHP:为什么声明(ticks = 1)打印4次

时间:2017-01-25 06:28:54

标签: php

我正在学习php declare statement.I播下以下php代码:

<?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);   
}

?>

输出:

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

我无法理解为什么"tick_handler() called"正在打印4次以及为什么" tick_handler() called 3"出现在第3次打印时。请帮我简单解释。谢谢

1 个答案:

答案 0 :(得分:1)

实际上你因为你的代码结构而感到困惑。它需要在下面点击: -

<?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
}

?>

输出: - https://eval.in/723678

注意: - 在链接的第二个示例中可以找到更清晰的图片: - http://php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks