检查未定义的对象属性时,组合isset和is_null会失败

I'm trying to combine isset and is_null in one function for ease of use

My approach:

class sys {

  public static function is_null(&$variable) {

    // if it's not set
    if (!isset($variable)) {
      return true;
    }

    // if array
    if (is_array($variable)) {
      return (boolean) (count($variable) < 1);
    }

    // if string
    return (boolean) (strlen($variable) < 1);
  }

}

The problem I'm having when i use it within an object is following exception:

ErrorException [ Notice ]: Indirect modification of overloaded property xxx has no effect.

For ease of use? The equivalent is return !isset($var) || empty($var);. is that so hard?

The thing that you need to realize when building a function like this, is that isset() is not a function. It's a language construct. So you can't pass a variable to a function, and then call isset on that variable (well, without generating a notice at least).

Secondly, there's no need to cast to boolean in :return (boolean) (strlen($variable) < 1);. It's exactly the same as return strlen($variable) < 1;.

Third, there's no reason to count() or use strlen(), since that's exactly what empty() was designed to check for.

Fourth, there's no reason at all to pass the argument by reference. It won't change anything, and it's needlessly creating references where there's no reason to. Just take the argument as normal (it won't use any more memory thanks to copy-on-write).

All in all, I would suggest not making this sort of "helper" function. Just use !isset($var) || empty($var) if you want to check if it's empty. It's clearer, makes more semantic sense, and frankly isn't duplicating effort. And if you don't care about the notice, you can just replace the entire call with if (empty($variable))...

But if you do use this kind of function, I'd suggest changing the name. It will return true even if the variable is not null, so calling the function is_null is down right misleading. Perhaps is_empty would be better...

just use empty()