非null if语句的最佳实践


The best practice for not null if statements

我一直在写"如果这个变量不是空的"语句,比如:

if ($var != '') {
// Yup
}

但我问过这是否正确,这并没有给我带来任何问题。以下是我在网上找到的答案:

if (!($error == NULL)) {
/// Yup
}

事实上,这看起来比我的方法要长,但它更好吗?如果是,为什么?

而不是:

if (!($error == NULL))

简单操作:

if ($error)

有人会认为第一个更清楚,但实际上更具误导性。原因如下:

$error = null;
if (!($error == NULL)) {
    echo 'not null';
}

这是意料之中的事。然而,接下来的五个值将具有相同的(对许多人来说,出乎意料的)行为:

$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;

第二个条件if ($error)更清楚地表明,涉及类型转换

如果程序员想要求值实际上是NULL,他应该使用严格的比较,即if ($error !== NULL)

准确地知道变量中有什么是很好的,尤其是当您检查未初始化的vs null或na vs true或false vs empty或0时。

因此,正如webbiedave所提到的,如果检查null,请使用

$error !== null
$error === null
is_null($error)

如果检查初始化,如shibly所说的

isset($var)

如果检查true或false、0或空字符串

$var === true
$var === 0
$var === ""

由于字符串函数往往不一致,所以我只将empty用于'和nulls。如果检查空

empty($var)
$var  // in a boolean context
// This does the same as above, but is less clear because you are 
// casting to false, which has the same values has empty, but perhaps
// may not one day.  It is also easier to search for bugs where you
// meant to use ===
$var == false

如果语义上未初始化的值与上面的某个值相同,则将开头的变量初始化为该值。

$var = ''
...  //some code
if ($var === '') blah blah.

为什么不

if (!$var)

有几种方法:

<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>

另一个:

<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}
?>

检查是否为空:

<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>