PHP有两个(我知道,如果算了三个isset()
)方法来确定一个值是否为null:is_null()
和=== null
.我听说过,但没有证实,这=== null
更快,但在代码审查中有人强烈建议我使用,is_null()
因为它是专门为空评估目的而设计的.他也开始谈论数学或其他什么.
无论如何,is_null()
显然较慢的事实也让我相信它做得更多=== null
而且可能更受欢迎.有没有理由使用其中一个?总是首选吗?怎么样isset()
?
作为可能无法解决这个问题的附录,那么isset()
对战is_null()
呢?似乎所有人isset()
都会压制通知,所以除非你真的想要一个未定义变量的通知,否则任何理由都可以使用is_null()
?如果你知道变量当时被初始化了怎么样?
最后,是否有任何数学理由,更喜欢is_null()
了=== null
?关于null无法比较的东西?
Nik*_*kiC 185
有绝对没有在两者之间的功能差异is_null
和=== null
.
唯一的区别是,这is_null
是一个功能,因此
array_map('is_null', $array)
.就个人而言,我null ===
随时都可以使用,因为它更符合false ===
和true ===
检查.
如果你愿意,你可以检查代码:is_identical_function
(===
)和php_is_type
(is_null
)做同样的事情的IS_NULL
情况.
相关isset()
语言构造在执行null
检查之前检查变量是否实际存在.所以isset($undefinedVar)
不会发出通知.
还要注意,即使值是isset()
有时可能返回- 这是在重载对象上使用时的情况,即如果对象定义了一个即使偏移量返回的/ 方法(这实际上很常见,因为人们使用在/ ).true
null
offsetExists
__isset
true
null
array_key_exists
offsetExists
__isset
jpr*_*itt 12
正如其他人所说,使用===
和之间存在时差is_null()
.做了一些快速测试并得到了这些结果:
<?php
//checking with ===
$a = array();
$time = microtime(true);
for($i=0;$i<10000;$i++) {
if($a[$i] === null) {
//do nothing
}
}
echo 'Testing with === ', microtime(true) - $time, "\n";
//checking with is_null()
$time = microtime(true);
for($i=0;$i<10000;$i++) {
if(is_null($a[$i])) {
//do nothing
}
}
echo 'Testing with is_null() ', microtime(true) - $time;
?>
Run Code Online (Sandbox Code Playgroud)
给出结果
使用=== 0.0090668201446533进行测试
使用is_null()0.013684034347534进行测试
我不能说使用is_null
或更好=== null
。但是isset
在数组上使用时要注意。
$a = array('foo' => null);
var_dump(isset($a['foo'])); // false
var_dump(is_null($a['foo'])); // true
var_dump(array_key_exists('foo', $a)); // true
Run Code Online (Sandbox Code Playgroud)
它们都有自己的位置,尽管只有isset()可以避免未定义的变量警告:
$ php -a
Interactive shell
php > var_dump(is_null($a));
PHP Notice: Undefined variable: a in php shell code on line 1
bool(true)
php > var_dump($a === null);
PHP Notice: Undefined variable: a in php shell code on line 1
bool(true)
php > var_dump(isset($a));
bool(false)
php >
Run Code Online (Sandbox Code Playgroud)
您需要isset()
如果变量可能是没有定义。当没有定义的变量或返回false === null
(是的,这是丑陋的)。只有isset()
和empty()
如果变量或数组元素不存在不引发E_NOTICE。
is_null
和之间没有真正的区别=== null
。我认为===
要好得多,但是当您例如call_user_func
出于某种可疑原因需要使用时,您必须使用is_null
.