PHP - reversed order in if statement

2019-02-16 19:02发布

This is a question that is bugging me for a long time and can't find any answer... Noticed it's used quite a lot by Zend Framework Developers,

What is the difference between following 2 "if" statements? :

if (null === $this->user) { ... }

if ($this->user === null) { ... }

To me the first one looks kinda odd ;]

Thanks for answer.

7条回答
相关推荐>>
2楼-- · 2019-02-16 19:49

It is a good practice for writing if statement. Consider this code:

if (10 == $var) {
  echo 'true';
} else {
  echo 'false';
}

If you forgot one equal sign:

if (10 = $var) { }

Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:

if ($var = 10) { }

will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.

查看更多
登录 后发表回答