通过 __get() 通过引用返回 null [英] Return null by reference via __get()

查看:58
本文介绍了通过 __get() 通过引用返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速规格:

PHP 5.3error_reporting(-1)//最高

我正在使用 __get() by reference 技巧来神奇地访问对象中任意深度的数组元素.

快速示例:

公共函数 &__get($key){返回 isset($this->_data[$key])?$this->_data[$key]: 空值;}

这不起作用,因为当 $key 未设置时,它会尝试通过引用返回 null,这当然会抛出 只应通过引用返回变量引用... 我尝试将其修改如下:

公共函数 &__get($key){$null = 空;返回 isset($this->_data[$key])?$this->_data[$key]: $null;}

虽然仍然不起作用,我假设将 $null 设置为 null 本质上是 unset() .>

我能做什么?谢谢!

<小时>

只是想我会推广这个问题,因为它有点相关(PHP 魔法和参考);__callStatic(), call_user_func_array(), 引用,和 PHP 5.3.1.我还没有找到答案……除了修改 PHP 核心.

解决方案

这与 null 无关,而是与三元运算符有关:

if/else 重写它不会抛出通知:

公共函数 &__get($key){$null = 空;如果 (isset($this->_data[$key])) {返回 $this->_data[$key];} 别的 {返回 $null;}}

三元运算符不能导致引用.它们只能返回.

Quick specs:

PHP 5.3
error_reporting(-1) // the highest

I'm using the __get() by reference trick to magically access arbitrarily deep array elements in an object.

Quick example:

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

This doesn't work as when the $key isn't set, it tries to return null by reference, which of course throws Only variable references should be returned by reference ... I tried modifying it as follows:

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

Still doesn't work though, I'm assuming that setting $null to null essentially unset()s it.

What can I do? Thanks!


Just figured I'd promote this question, as it's somewhat relevant (PHP magic and references); __callStatic(), call_user_func_array(), references, and PHP 5.3.1. I've yet to find an answer ...besides modifying the PHP core.

解决方案

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.

这篇关于通过 __get() 通过引用返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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