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?
null variable: It speedily frees the memory.
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.
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.
PHP considers null is equal to zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With