Return null by reference via __get()

耗尽温柔 提交于 2019-12-05 10:13:15

This has nothing to do with null, but rather the ternary operator:

Rewriting it with an if/else won't throw the notice:

public function &__get($key)
{
    $null = null;
    if (isset($this->_data[$key])) {
        return $this->_data[$key];
    } else {
        return $null;
    }
}

Ternary operators cannot result in references. They can only return values.

Why return null explicitly? If $key doesn't exist in $this->_data it's going to return NULL anyway?

I recommend using the following and adjust your logic on the other end. You're probably already checking for null now. You could change it to empty() or some other variant. Or use exceptions as suggested by Matthieu.

public function &__get($key){
    return $this->_data[$key];
}

I had this problem, but I ended up realizing that I shouldn't return null when the key wasn't found, but throw an exception (because I was accessing an unknown attribute after all).

But maybe that's not what you want to do, I just wanted to share that.

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