Combining isset and is_null fails when checking undefined object property

僤鯓⒐⒋嵵緔 提交于 2020-01-03 04:54:06

问题


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.


回答1:


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...




回答2:


just use empty()



来源:https://stackoverflow.com/questions/5677648/combining-isset-and-is-null-fails-when-checking-undefined-object-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!