【问题标题】:PHP ArrayAccess - multidimensional array and offsetGet with referencePHP ArrayAccess - 多维数组和 offsetGet 参考
【发布时间】:2015-01-22 14:37:14
【问题描述】:

我阅读了很多关于ArrayAccess PHP 接口的过去问题,它的方法offsetGet 可以返回一个引用。我有一个实现这个接口的简单类,它包装了一个array 类型的变量。 offsetGet 方法返回一个引用,但是我收到一条错误消息 Only variable references should be returned by reference。为什么?

class My_Class implements ArrayAccess {
    private $data = array();

    ...

    public function &offsetGet($offset) {
        return isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : null;
    }

    ...
}

我希望能够在这个类中使用多维数组:

$myclass = new My_Class();

$myclass['test'] = array();
$myclass['test']['test2'] = array();
$myclass['test']['test2'][] = 'my string';

【问题讨论】:

  • 因为你返回 NULL 未绑定到一个变量,如果你将它重写为 if(!isset( $this->data[ $offset ]) $this->data[ $offset ] = null; return $this->data[ $offset ]; 有帮助吗? /懒得测试
  • 您的函数返回表达式的结果,而不是引用。 & null 引用是不可能的。试试临时变量。

标签: php arrayaccess


【解决方案1】:

在这段代码中:

public function &offsetGet($offset) {
    $returnValue = isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : null;
    return $returnValue;
}

$returnValue$this->data[$offset] 的副本,而不是参考。

你必须让自己成为一个引用,为此你必须用 if 语句替换三元运算符:

public function &offsetGet($offset) {
    if (isset($this->data[$offset]) {
        $returnValue &= $this->data[$offset]; // note the &=
    }
    else {
        $returnValue = null;
    }
    return $returnValue;
}

应该可以解决问题。

对于不存在的情况,我宁愿抛出一个异常,就像你在请求一个不存在的数组键时得到的那样。 由于您返回的值不会是参考,

$myclass['non-existing']['test2'] = array();

大概会抛出一个indirect overloaded modification 错误,因此应该被禁止。

【讨论】:

    【解决方案2】:

    方法“&offsetGet”返回一个变量的引用(指针)。

    您需要将方法签名从“&offsetGet”修改为“offsetGet”,或者使用变量来保存返回值。

    // modify method signiture
    public function offsetGet($offset) {
        return isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : null;
    }
    
    // or use a variable to hold the return value.
    public function &offsetGet($offset) {
        $returnValue = isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : null;
        return $returnValue;
    }
    

    【讨论】:

    • 我不能使用第一个语句,因为它返回的是数组的副本而不是原始的。第二个语句抛出一个新错误:间接修改 My_Class 的重载元素没有效果
    • 给我堆栈上的上下文。什么叫 offsetGet?
    • 在问题中。我正在创建一个新的类实例,然后尝试在数组中设置一些数据
    【解决方案3】:

    我认为这是因为您返回的是表达式的结果,而不是变量。 尝试写出 if 语句并返回实际变量。

    php manual -> second note

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 1970-01-01
      • 2019-01-12
      • 2012-02-05
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多