Why do I see peo开发者_Python百科ple doing if (false !== $var) {
instead of if (false === true) {
This answer consists of three parts:
- The difference in order between (false == $var) and ($var == false)
- The difference between == and ===
- Why you see people doing
(false !== $var)
instead ofif (false === true)
1. The difference in order between (false == $var) and ($var == false)
Because an often-made mistake is forgetting to put two =
which results in an accidental attribution instead of comparison, some programmers decide to always put the invariable part of the equation on the left-side. This way, the accidental assignment is impossible and you don't risk getting
if ($var = false)
which assigns false to the variable $var
and will always evaluate false instead of the desired
if ($var == false)
2. The difference between == and ===
The ===
or !==
compares the variable's type as well as its value, whereas ==
and !=
compare value and convert types where needed.
Example:
0 == false // true
1 == true // true
0 === false // false
1 === true // false
0 !== false // true
0 !== true // true
false === false // true
false === true // false
$var !== FALSE
is used because a lot of built-in PHP functions return FALSE
on error, and a value on success. The value returned may be the same value as TRUE
but it may not be the same type.
3. Why you see people doing (false !== $var)
instead of if (false === true)
Your question itself made people snicker (that's why OrangeDog's comment was upvoted that much): if people did if (false === true)
, it would equal if(false)
and would never execute the enclosing block. It still happens though, for example in JavaScript when part of the code is generated in a serverside-language, like PHP.
because its something completely different.
the first code part opens an if clause only if var is not false. it may be zero, null or an empty string. but not of type boolean and false.
the second one is a contradiction that can never ever happen.
Why do I see people doing if (false !== $var) {
Logic comparisons are a common foil for beginning programmers, and it is typical to see
$var = false
when what was meant
$var == false
So standard practice is to encourage programmers to always place variables on the right hand side, since $var=true
is technically legal, but produces unexpected behavior, while true=$var
is not legal and throws an error.
In your case it looks like ugly, if sensible, programming habits were taken to their logical end.
精彩评论