Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

zend framework - PHP - reversed order in if statement

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,

What is the difference between following 2 "if" statements? :

if (null === $this->user) { ... }

if ($this->user === null) { ... }

To me the first one looks kinda odd ;]

Thanks for answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

is the fact that if you mistype and write = instead of == you will get an error, while

($this->user = null)

instead of

($this->user == null)

works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)

and I guess it just extended as a habit to the strict comparison operator (===)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...