2013-05-29 53 views
1

這是條件語句:爲什麼在這個條件語句的變量前面有一個感嘆號?

$comments = get_value_of_comments_as_string(); 

if(!$comments == "on"){...} 

什麼是$comments變量之前的!點特別是因爲$comments的目的持有的字符串。

編輯:這個條件似乎不是一個錯字,因爲原來的編碼器有這些條件語句中的5個。都是這樣的。

回答

12

!是邏輯否定運算符(或不),所以基本上它將真值改爲假和假值爲真。

我敢肯定,作者的意圖是成爲

!($comments == "on") // if comments == "on" return false 

但什麼他實際上說的是

(!$comments) == "on") // if not comments == "on" ... this test will only succeed if comments is null or an empty string. 

一個表達,這是

$comments != "on" 

更好的方法這種行爲是因爲! ==具有更高的優先級,因此它將在==之前進行評估。

+0

so if(!$ comments ==「on」)'等價於if((!!comments)==「on」)'? – pogidude

+0

是...測試它,看看 – Orangepill

+0

我應該更正我的答案,因爲如果$ comments是一個空字符串或任何其他falsey值測試將爲真 – Orangepill

相關問題