开发者

Is there any benefit of using null first in PHP?

开发者 https://www.devze.com 2023-04-02 02:09 出处:网络
Possible Duplicate: Why do some experienced programmers write comparisons with the value before the variable?

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开发者_Python百科 coding standard I have overlooked?


It prevents you from accidentally assigning the value to a variable, especially when only using loose type comparison (==):

if (self::$_instance = NULL) { … } // WHOOPS!, self::$_instance is now NULL

This style of conditions is often called yoda conditions. Performance wise there is no difference, both statements are equivalent.


This is mainly to prevent accidental assignment:

if (self::$_instance = null) ... //oops!


There's no significant performance difference. The usual benefit of writing expressions in this way is defensive programming. We want to avoid accidentally using an assignment instead of equality comparison:

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

Woops!


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.


It's not particular to null - I've seen many coders prefer to write their expressions this way round:

if(8 == 4 * 2) {

It's just a preference which some people think is clearer.

0

精彩评论

暂无评论...
验证码 换一张
取 消