2014-11-24 43 views
2

考慮下面的代碼...分號後,如果在PHP中的條件 - 代碼仍然有效

if ($condition); // <-- do not miss semicolon here! 
{ 
    //... 
} 

塊的工作內部的代碼之後。有人可以解釋我爲什麼沒有收到語法錯誤嗎?

+6

因爲如果(...);意味着條件什麼都不做 – 2014-11-24 13:49:31

+0

在代碼中使用大括號是不正常的,它不是一個語法錯誤。他們應該只允許在一些街區之後,而不是在任何地方。完全解析器對我來說錯了嗎? – 2014-11-24 14:32:41

回答

3

我會建議你在這兒讀手冊:

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

要你直接問爲什麼:you don't get a syntax error
- >簡單,因爲沒有語法錯誤!

你的代碼是正確的,這意味着:

if ($condition) ; 
// ^condition ^if true execute that line 

//same as 
if ($condition) 
    ; 

//same example with other line if the condition is true 
if ($condition) echo "true"; 

if ($condition) 
    echo "true"; 

所以你行,如果條件爲真該被執行是這樣的:;和意味着什麼。

這是一樣的:;;;;;它只是沒有!

在大多數情況下,你使用if語句是這樣的:

if ($condition) 
    echo $result; 


if ($condition) { 
    echo $result; 
} 

if ($condition) echo $result; 
1

becuse你可以寫裏面{ }任何代碼,而無需如果

檢查這個例子:

<?php 

{ 
    echo 'Hi Man'; // it print Hi Man (without using if statment) 
} 

?> 
相關問題