为什么php中最后一个语句的分号是可选的?

Why is the semicolon optional in the last statement in php?

当我在编辑器中 运行 以下代码时,我感到很惊讶:

<?php

    echo "hello";
    echo "world"

?>

很容易看出,代码中缺少一个分号 (;),但它仍然有效!

这是如何工作的,为什么 ; 在这里是 {0,1}?

因为关闭标记暗示分号。您可以在 Instruction separation.

下的手册中阅读更多相关信息

引自那里:

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

证明这一点的例子:

1。末尾缺少分号但带有结束标记的脚本:

<?php
    echo "1";
    echo "2"
          //^ semicolon missing
?>

输出:

12

2。末尾缺少分号但没有结束标记的脚本:

<?php
    echo "1";
    echo "2"
          //^ semicolon missing (closing tag missing)

输出:

Parse error: syntax error, unexpected end of file, expecting ',' or ';' in

因为分号告诉解析器您已经到达该指令的末尾。它让它知道下一段文本是一条新指令。然而,结束标记告诉它我们在所有指令的末尾,您不需要解析任何其他内容。因为我们不解析任何其他内容,所以我们不需要指令结束分号,这是隐含的。

那是因为分号不是终止语句的符号。

看起来像那样,因为它几乎总是出现在语句的末尾。

注意几乎总是...可能是一个提示。

试图摆脱不对称,我们可以说它是总是在语句之间!

这直接引出了分号的真正含义:它不终止语句——它分隔语句
很显然,在最后一句之后,就没有什么可以分开的了。


(大多数语言无论如何都允许在块的末尾使用分号,以防止相关的琐碎错误。这可以通过丢弃分号来完成,或者更明确地说,通过在分号后插入不执行任何操作的命令来完成.)