Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for ordering an if statement this way?

Why form if statements like...

if (null === $this->foo){...}
if (0 === count($bar)){...}

rather than...

if ($this->foo === null){...}
if (count($bar) === 0){...}

I've noticed this in the code of a number of coders and projects I respect but I don't know why they do it this way. I do it the second way as it follows my thinking "If this value is identical to null then..." whereas asking "If null is identical to this value..." seems a bit less obvious to me. So... why?

like image 960
Lothar Avatar asked Dec 06 '22 00:12

Lothar


1 Answers

It's intended to ensure that you don't accidentally put if(this->foo = null) instead of the double ==.

This is an error which PHP will catch for you automatically

if (null = $foo) {}

while this is probably a mistake (although it can be deliberate and useful sometimes)

if ($foo = null) {}

So, by ordering your conditions in such a way, you protect yourself against accidentally assigning a value instead of comparing them.

like image 168
El Yobo Avatar answered Dec 23 '22 15:12

El Yobo