Variable before or after value in IF statement
Is there a difference between these two statements:
if ($a == 'hello') { ... }
an开发者_运维知识库d
if ('hello' == $a) { ... }
I've noticed applications like Wordpress tend to use the latter, whereas I usually use the former.
I seem to remember reading something a while ago giving justification for the latter, but I can't recall the reasoning behind it.
There is no difference. It is used so that an error is thrown in case you accidentally make an assignment instead of a comparison:
if('hello' = $a)
if($a = 'hello')
would assign to the variable and not throw an error.
It might also be used to explicitly show that if you have an assignment in an if
statement, you really want to have it there and it is not a mistake (consistency).
The justifikation for the latter is that if you mistakenly type =
instead of ==
(assignment instead of comparision) you'll get compiler error (can't assign to constant).
精彩评论