在PHP中首先使用null有什么好处? [英] Is there any benefit of using null first in 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();
}
特别是这一行...
if (null === self::$_instance) {
为什么在if
语句的第一个参数中使用null
而不是相反?...
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?
推荐答案
它可以防止您意外地将值分配给变量,尤其是在仅使用松散类型比较(==
)时:
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
这种条件类型通常称为 yoda条件.在性能方面没有区别,两条语句是等效的.
This style of conditions is often called yoda conditions. Performance wise there is no difference, both statements are equivalent.
这篇关于在PHP中首先使用null有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!