检查未定义的对象属性时,组合isset和is_null失败 [英] Combining isset and is_null fails when checking undefined object property

查看:98
本文介绍了检查未定义的对象属性时,组合isset和is_null失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 isset is_null 组合在一个函数中,以便于使用

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

我的方法:

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 [注意]:间接修改重载属性xxx无效。

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


推荐答案

为便于使用?等价于 return!isset($ var)|| empty($ var);

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

构建这样的函数时需要意识到的是 isset() 不是功能。这是一种语言结构。因此,您无法将变量传递给函数,然后在该变量上调用isset(好吧,至少不会产生通知)。

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

第二,不需要在以下类型中强制转换为布尔值: return(boolean)(strlen($ variable)< 1); 。它与 return strlen($ variable)<完全相同。 1;

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

第三,没有理由 count()或使用 strlen(),因为这正是 empty()旨在检查的内容。

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

总而言之,我建议进行这种帮助功能。只需使用!isset($ var)||如果要检查是否为空,则为空($ var)。它更清晰,更有意义,并且坦率地说,它并不重复工作。而且,如果您不在乎通知,可以将整个调用替换为 if(empty($ variable)) ...

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

但是,如果您确实使用了这种功能,我建议您更改名称。即使变量不是 null ,它也会返回 true ,因此调用函数 is_null 是向下的误导。也许 is_empty 会更好...

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

这篇关于检查未定义的对象属性时,组合isset和is_null失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆