PHP: using empty() for empty string?

前端 未结 3 1601
心在旅途
心在旅途 2020-12-10 16:38

I recently discovered this interesting article by Deceze.
But I\'m a bit confused by one of its advises:

never use empty or isset for variables th

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 17:01

    You should not use empty (or isset) if you expect $foo to exist. That means, if according to your program logic, $foo should exist at this point:

    if ($foo === '')
    

    Then do not do any of these:

    if (isset($foo))
    if (empty($foo))
    

    These two language constructs suppress error reporting for undefined variables. That's their only job. That means, if you use isset or empty gratuitously, PHP won't tell you about problems in your code. For example:

    $foo = $bar;
    if (empty($føø)) ...
    

    Hmm, why is this always true, even when $bar contains the expected value? Because you mistyped the variable name and you're checking the value of an undefined variable. Write it like this instead to let PHP help you:

    if (!$føø) ...
    

    Notice: undefined variable føø on line ...

    The condition itself is the same, == false (!) and empty produce the same outcome for the same values.

    How exactly to check for an empty string depends on what values you do or don't accept. Perhaps $foo === '' or strlen($foo) == 0 is the check you're looking for to ensure you have a string with something in it.

提交回复
热议问题