問(wèn)題描述
這個(gè)問(wèn)題困擾了我很久,一直找不到答案...注意到它被 Zend 框架開(kāi)發(fā)人員大量使用,
This is a question that is bugging me for a long time and can't find any answer... Noticed it's used quite a lot by Zend Framework Developers,
以下兩個(gè)if"語(yǔ)句有什么區(qū)別?:
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
對(duì)我來(lái)說(shuō)第一個(gè)看起來(lái)有點(diǎn)奇怪;]
To me the first one looks kinda odd ;]
感謝您的回答.
推薦答案
這與您的腳本的工作方式?jīng)]有區(qū)別,它只是一個(gè)編碼標(biāo)準(zhǔn),一個(gè)建議
This is not a difference for the way your script works, it's just a coding standard, a recommendation
推薦使用這種方式的原因:
The reason why it is recommended to use it this way:
if (null == $this->user)
的事實(shí)是,如果你輸入錯(cuò)誤并寫(xiě) = 而不是 == 你會(huì)得到一個(gè)錯(cuò)誤,而
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
代替
($this->user == null)
有效但會(huì)導(dǎo)致奇怪的錯(cuò)誤(賦值和最終值被評(píng)估為 bool 而不是比較)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
我猜它只是作為一種習(xí)慣擴(kuò)展到嚴(yán)格比較運(yùn)算符 (===)
and I guess it just extended as a habit to the strict comparison operator (===)
更新:因?yàn)槲野l(fā)現(xiàn)即使在我發(fā)布答案 3 年后該線程上仍有一些活動(dòng),所以我想我會(huì)添加一些我忘記提及的內(nèi)容.這種類型的符號(hào)稱為 yoda conditions
,您可以在 this 上閱讀有關(guān)它的更多信息例如維基百科頁(yè)面.
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions
, you can read more about it on this wikipedia page for example.
這篇關(guān)于PHP - if 語(yǔ)句中的倒序的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!