为什么PHP不会抛出一个解析错误?

时间:2021-05-27 15:39:47

There are lots of "Why does PHP throw an error here?" questions. Well, this is a little different. I found the following code while reworking some code written by a coworker:

这里有很多“为什么PHP会抛出错误?”这有点不同。我在重写同事写的代码时发现了以下代码:

foreach($arr as $key => $value) {http://google.com/
  echo $value;
  // ...
}

My first thought: "Umm...how embarrassing; he must have accidentally pasted that in there..." followed by: "Wait...there's no way this code actually runs...that should be a syntax error". And yet:

我的第一个念头:“嗯…多么尴尬的;他一定是不小心把那个贴在那里了……这段代码实际上不可能运行……这应该是一个语法错误。然而,:

 $ php -l test.php
 No syntax errors detected

And indeed, (like so much PHP code that seemingly shouldn't run) it runs in production without trouble. So I did a little testing:

实际上,(就像很多看起来不应该运行的PHP代码一样),它在生产环境中运行时没有任何问题。所以我做了一些测试

foreach($arr as $key => $value) {http://google.com/ <-- original, no error
foreach($arr as $key => $value) {http: <-- also no syntax error
foreach($arr as $key => $value) {http  <-- bingo! "Unexpected T_ECHO..."

What little tidbit of PHP's grammar is producing such strange results?

PHP的语法中有什么小的花边新闻产生如此奇怪的结果呢?

(I am using PHP 5.3.5)

(我使用的是PHP 5.3.5)

1 个解决方案

#1


7  

The http: is being interpreted as a label (which are used for goto statements), and the //google.com/ as a comment (which can easily be seen through syntax highlighting).

http:被解释为一个标签(用于goto语句)和//google.com/作为注释(通过语法突出显示可以很容易地看到)。

Documentation on goto:

在转到文档:

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label.

goto操作符可用于跳转到程序的另一部分。目标点由一个标签和一个冒号指定,指令以goto形式给出,后面跟着预期的目标标签。

#1


7  

The http: is being interpreted as a label (which are used for goto statements), and the //google.com/ as a comment (which can easily be seen through syntax highlighting).

http:被解释为一个标签(用于goto语句)和//google.com/作为注释(通过语法突出显示可以很容易地看到)。

Documentation on goto:

在转到文档:

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label.

goto操作符可用于跳转到程序的另一部分。目标点由一个标签和一个冒号指定,指令以goto形式给出,后面跟着预期的目标标签。

相关文章