开发者

PHP: Condition Format - (6 == $var) or ($var == 6)?

I was browsing these PHP Coding Guidelines (a bit outdated but very interesting), and found this:

Condition Format

Always put the constant on the left hand side of an equality/inequality comparison. For example: if ( 6 == $errorNum ) ...

One reason is that if you leave out one of the = signs, the parser will find the error for you. A second reason is that it puts the value you are looking for right up front where you can find it instead of buried at the end of your expression. It takes a little time to get used to this format, but then it really gets useful.

I have been using ($var == 6) for years now and the idea of putting them the other way around is horrifying. But as mentioned, this takes a bit time to get used to and is supposed to have clear benefits. We are just writing up standard at our company so if we want to change this, this is the moment to do that. But I'd like to hear if other have experience with this particular format. Any opinions?

EDIT

I am interested in people's experience with making this switch. To me, and most likely to others, this looks like a big change that you need to get used to. But it looks interesting. So the question to those who have switched: can you recommend this change?开发者_运维问答


6 == $var has a real advantage that $var == 6 does not. There is nothing horrifying about it at all, it just looks different. You should get used to it and use it. In fact, I haven't gotten used to it yet and I forget about it frequently. You really have to think about it and use it since the opposite is so common.

The advantage, in case you didn't know, is to prevent simple syntactical mistakes, thus:

if ($var = 6) {} //weird semantic error
if (6 = $var) {} //parse error
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜