问题
Is one more readable than the other? At first, I disliked the false ===
approach but as I see it more and more often, I'm warming up to it. I'm pretty sure they return identical results.
回答1:
I greatly prefer
false === $var
Namely because sometimes you are only using equality and not looking for identity.
In which case you write
false == $var
But sometimes you aren't at the top of your game, and might write
false = $var
which will give an immediate error, and let's you fix it right away.
However, if you type
$var = false
you end up beating your head against a wall for an hour trying to figure out why your script isn't working right.
回答2:
There's absolutely no functional difference.
I usually prefer to place the variable first, and the constant value second. Because that makes sense (When you speak it out loud, would you say "I test that the variable is false"? Or "I test that false is equal to the variable"?)
回答3:
A much better software engineer than me taught me about this. Long story short, placing the constant first is a best practice, although it may look weird at first. I say that it's a best practice because it results in the most predictable outcomes:
$var = null;
if (false === $var) { // NullPointerException is not thrown; only evaluates to "true" if the value "false" was assigned to $var
...
}
if ($var === false { // NullPointerException will be thrown
...
}
if (false = $var) { // Parse Error
...
}
if ($var = false) { // the value false is assigned to $var
...
}
来源:https://stackoverflow.com/questions/13222070/whats-the-difference-between-false-var-and-var-false