Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit of using null first in PHP?

Tags:

syntax

php

Possible Duplicate:
Why do some experienced programmers write comparisons with the value before the variable?

I am just curious about this: in most frameworks/opensource projects I have studied, I often seen code like this...

<?php

if (null === self::$_instance) {
    self::$_instance = new self();
}

In particular this line...

if (null === self::$_instance) {

Why use null in the first argument of the if statement instead of the other way around?...

if (self::$_instance === null) {

I realize there is probably no performance increase or anything like that. Is this just a preference or is it some kind of coding standard I have overlooked?

like image 688
JasonDavis Avatar asked Aug 31 '11 17:08

JasonDavis


People also ask

What's better at freeing memory with PHP unset () or $var null?

null variable: It speedily frees the memory.

IS null considered false PHP?

It's language specific, but in PHP :Null means "nothing". The var has not been initialized. False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

Can we use null in PHP?

Null is a special data type in PHP which can have only one value that is NULL. A variable of data type NULL is a variable that has no value assigned to it. Any variable can be empty by setting the value NULL to the variable.

Is 0 and null the same in PHP?

PHP considers null is equal to zero.


1 Answers

It's to help you get your code right.

If you do this, your code will work, but the effect will be a long way from what you want:

if (self::$instance = null) {

The conditional will always fail (because the = operator returns the value set, and it is falsy) but self::$instance will now be set to null. This isn't what you want.

If you do this:

if (null = self::$instance) {

your code will fail to work, because you can't use null (or any literal such as a string or an integer) on the left-hand-side of an assignment. Only variables can be the left-hand-side of the = operator.

So if you mistype the == as =, you get a parse error and your code completely doesn't work. This is preferable to a mystifying and hard-to-track-down bug.

like image 88
lonesomeday Avatar answered Sep 21 '22 01:09

lonesomeday