PHP(4.3 和 5.3 版)缺失;在继续使用打印但不适用于回声之后

PHP (v 4.3 and 5.3) missing ; after continue works with print but not works with echo

我正在测试 PHP 的较低版本 v4.3 和 v5.3 的代码,这是 continue after without 的一些代码分号。它的作品并给出奇怪的输出。

for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
//Output: 2 its strange 

但是 echo 会抛出错误 Parse error: syntax error, unexpected 'echo' (T_ECHO)

for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    echo "$i\n";
}
//Output:  Parse error: syntax error, unexpected 'echo' (T_ECHO)

很确定这是因为,在 php 的早期版本中,您可以

function f(){return 2;}
for($i=0;$i<9;++$i){
for($ii=0;$ii<99;++$ii){
continue f();
}
}

然后它将继续 f() 返回的循环号(在本例中为 $i 循环。如果它返回 1,它将继续 $ii 循环) 在 PHP 的现代版本中,您可以对数字进行硬编码,但不能再对可变数字进行编码,它必须在编译时决定。和 print() returns int。 echo 没有,这就是你得到错误的原因,continue 的参数必须是一个 int。

原因是 continue 语句接受一个可选的整数(要继续的循环数),如果给出 none,则默认为 1。

由于没有分号,PHP 会将下一个表达式作为该整数。语言构造 print return 是一个整数,所以没关系。但是,echo 也是一种语言结构,但它没有 return 值。因此,当解析器正在寻找一个整数时,它会遇到一个没有 return 值的语言结构,它会感到困惑并引发错误。

真正的解决办法是加入分号,因为没有分号实际上是在潜在地改变continue.

的行为

(在这种情况下你不是,因为 print always returns one,但在其他情况下它实际上可能会在你的代码中引入错误。)

continue语句接受一个参数,所以你可以在它后面添加更多的表达式:

continue <foo>;

print 是一个表达式,可以用作其他语句的一部分,因此 continue print(); 是有效语法。这也是为什么输出2,当$i == 2.

时执行单个语句continue print $i;

echo 是一个语句,不能 用作其他表达式的一部分,<anything> echo 是无效语法。

原因:输出:2

because the entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

http://php.net/manual/en/control-structures.continue.php