The best practice for not null if statements

前端 未结 4 1715
你的背包
你的背包 2021-02-13 16:32

I\'ve been writing my \"If this variable is not empty\" statements like so:

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

But I\'ve asked if this is correct, it

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 16:34

    Rather than:

    if (!($error == NULL))
    

    Simply do:

    if ($error)
    

    One would think that the first is more clear, but it's actually more misleading. Here's why:

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

    This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:

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

    The second conditional if ($error) makes it more clear that type casting is involved.

    If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)

提交回复
热议问题