duancai1904 2014-03-31 01:00
浏览 16
已采纳

为什么if(陈述); 编译并运行? [重复]

This question already has an answer here:

I've always been wondering about this since I began learning PHP. As many other new-beginners, I placed semicolons all over the place, and for some reason, placing them after an if statement compiles and runs, but not like one would expect.

Example:

<?php
$foo = "bar";

if ($foo == "bar") // Correct way
    echo "OK";

if ($foo == "bar"); // Incorrect way
    echo "OK";

if ($foo == "derp"); // Incorrect way again
    echo "NO";
?>

This will output:

OKOKNO

Why is this? What is the intended usage for this? Just a twerk left in the code that for some reason has never been fixed? It looks like the compiler just skips the entire if-statement all together.

</div>
  • 写回答

5条回答 默认 最新

  • dpmopn8542 2014-03-31 01:04
    关注

    Because the PHP interpreter is looking for one statement after the if(...) to execute if the condition is evaluated to true. Appending the semicolon tells the interpreter that you're done with the statement. You've effectively told PHP to execute a no-op statement when the condition holds true. The echo isn't even part of the if-statement anymore.

    It's equivalent to writing

    if($foo == "bar"){
    }
    echo "OK";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding