What's the difference between 'false === $

2019-01-29 06:10发布

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.

3条回答
混吃等死
2楼-- · 2019-01-29 06:56

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"?)

查看更多
Melony?
3楼-- · 2019-01-29 07:01

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.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-29 07:04

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
    ...
}
查看更多
登录 后发表回答