Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - reversed order in if statement

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.

like image 761
alchemication Avatar asked Jun 01 '12 11:06

alchemication


2 Answers

This is not a difference for the way your script works, it's just a coding standard, a recommendation

The reason why it is recommended to use it this way:

if (null == $this->user)

is the fact that if you mistype and write = instead of == you will get an error, while

($this->user = null)

instead of

($this->user == null)

works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)

and I guess it just extended as a habit to the strict comparison operator (===)

Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.

like image 127
mishu Avatar answered Nov 13 '22 02:11

mishu


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.

like image 32
flowfree Avatar answered Nov 13 '22 02:11

flowfree