简体   繁体   中英

php - which one is better approach null== or ==null

I saw many times that php developers use somthing like this:

if(null == $var){

}

while I use

if($var == null){

}

Are these two different? is there any reason to use each one? or it is a choice matter in any ways?

Simply null can't be assigned value null = $a , it will throw parsing error.

but any variable can have null as value. $a = null

So if you mistyped == to = in the second case, you have changed the value of $a and you check the if condition of the new value of $a which always evaluates to false.

Short answer, it's exactly the same thing. Long answer:

The C programming language allows assignment within the condition. eg

(i = 1)==1 is valid. This means that:

if (x = null)

is valid as well.

In some cases you intended to assign x = null but (most often) you just intended to compare x == null and mistyped.

Therefore developers in C (or C++) would do something like:

if (null == x) 

This is because if it was mistyped to if (null = x) it would not compile.

However in PHP this is no longer a valid reason since PHP is not compiled therefore such errors are not trapped early and this defeats the whole purpose of the reversed syntax.

However, the advantage of using it in PHP is that when you do hit that part of the code, it will error instead of running normally and will therefore inform you of the problem.

On the other hand in PHP you should really use === so typos would lead to == anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM