Difference between variable === value and value === variable?
a)
if(null === $object)
{
//take some action
}
if($object === null)
{
//take some action
}
I am in habit of doing like b) but in Zend-Framework I find everywhere they have done it like a) . Is there any benefits of it ??
Thanks.
No, there is no difference.
The latter is supposed to help to avoid silly typos when you write $a = null
instead of $a == null
(or $a === null
). In first case you'll get logical error, because of assignment instead of comparison, in second case - you'll get fatal error which will help you to find an issue sooner.
There is no difference, it is used to avoid mistakes (like setting variable to null
, not comparing them), however the null === $object
is often considered the Bad Way (c) to avoid typos.
The $object === null
expression is much more human-friendly then null === $object
'cause second one breaks nature reading order which is left-to-right. That's why even if there is no much difference for interpreter but it's a bit harder to read by a human. Involving some logic - if you use if..else statement how it should sounds like? "If null
equals $object
.. Wait a minute, null
is null
, how can it be equal to something else? Oh, Gee, we actually comparing right-handed value to left-handed one, it's reversed stuff. So, if $object
equals null
then we should..". And your think this way every time.
My conclusion is: use $value == const
every time you can! Long time ago people wrote if ($value = const)
but these times have passed. Now every IDE can tell ya about such simple errors.
b) is way more readable than a)
And a) is considered by some overcautious people as less error prone because of possible confusing ==
with =
.
But in case of three ='s I doubt anyone will confuse it with one.
This a choice by the developer to attempt to stop accidential assignment of values.
The functionality is exactly the same between the two methods of comparison but in the case of "a" it stops any accidential assignment of values as you cannot assign something to null.
The second method checks the value and type of variable against null
, The errors should be different in tow methods.
精彩评论