PHP中的is_null($ x)vs $ x === null

时间:2011-11-22 14:56:35

标签: php isnull

  

可能重复:
  What's the difference between is_null($var) and ($var === null)?

PHP有两个(我知道,有三个,如果你计算isset())方法来确定一个值是否为空:is_null()=== null。我听说过,但未确认,=== null速度更快,但在代码审核中,有人强烈建议我使用is_null(),因为它是专为空评估目的而设计的。他也开始谈论数学等等。

无论如何,is_null()显然较慢的事实也让我相信它的作用超过了=== null并且可能更受欢迎。有没有理由使用其中一个?总是首选吗?那么isset()呢?

作为可能无法解决此问题的附录,isset()is_null()有何关系?似乎所有isset()都会阻止通知,因此,除非您实际上想要通知未定义的变量,否则使用is_null()的任何理由?如果你知道变量当时已经初始化了怎么样?

最后,是否有任何数学上的理由偏好is_null()而不是=== null?关于null无法比较的东西?

7 个答案:

答案 0 :(得分:176)

is_null=== null之间的 绝对没有 功能差异。

唯一的区别是is_null是一个函数,因此

  1. 略慢(函数调用开销)
  2. 可以用作回调,例如array_map('is_null', $array)
  3. 就个人而言,我会尽可能使用null ===,因为它与false ===true ===检查更为一致。

    如果需要,您可以查看代码:is_identical_function===)和php_is_typeis_null)对IS_NULL案例做同样的事情


    相关的isset()语言构造在执行null检查之前检查变量是否实际存在。所以isset($undefinedVar)不会发出通知。

    另请注意,isset()有时可能会返回true,即使值为null - 这是在重载对象上使用时的情况,即对象是否定义{ {1}} / offsetExists方法返回__isset,即使偏移量为true(这实际上很常见,因为人们在null /中使用array_key_exists / offsetExists)。

答案 1 :(得分: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;
?>

给出结果

  

使用=== 0.0090668201446533进行测试

     

使用is_null()0.013684034347534进行测试

See the code in action

答案 2 :(得分:5)

他们都有自己的位置,但只有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 >

答案 3 :(得分:4)

如果可能未定义变量,则需要isset()。它在未定义变量时返回false或=== null(是的, 丑陋)。如果变量或数组元素不存在,则只有isset()empty()不会引发E_NOTICE。

is_null=== null之间并没有什么区别。我认为===更好,但是当你出于某种可疑原因需要使用call_user_func,您必须使用is_null

答案 4 :(得分:4)

&#39;我无法说出使用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

答案 5 :(得分:3)

===is_null是一样的。

根据this comment is_null,只有250ns慢。我认为因为函数比运算符慢。

答案 6 :(得分:2)

PHP documentationis_null, === null, isset进行了很好的讨论和实验。特别是阅读评论部分。