繁体   English   中英

避免通知:stdClass 中的未定义属性

[英]Avoid notice: Undefined property in stdClass

$a = (object)['foo' => 'bar'];
$a->baz;

$a->baz调用返回NULL但也会引发通知Undefined property.. 当属性不存在时,获取 null 对我来说很好,但是有没有办法抑制这个特殊的通知(来自配置或其他东西,而不是 if 语句或 @ 符号,这很明显)但继续看到其他通知?

一个可能的解决方案是创建一个使用__get魔术方法的自定义 std 类:

class customStdClass
{
    public function __get($name)
    {
        if (!isset($this->$name)) {
            return null;
        }

        return $this->$name;
    }

    public static function fromArray($attributes)
    {
        $object = new self();

        foreach ($attributes as $name => $value) {
            $object->$name = $value;
        }

        return $object;
    }
}

你可以像这样使用它:

$object = customStdClass::fromArray(['foo' => 'bar']);
echo $object->foo;
echo $object->baz; // no warning here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM