PHP ArrayAccess - 多维数组和偏移量获取与引用


PHP ArrayAccess - multidimensional array and offsetGet with reference

我读了很多关于PHP接口ArrayAccess问题,它是可以返回引用的方法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';

在此代码中:

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错误,因此应该被禁止。

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

请参阅 PHP 手册 -> 第二个注释

方法 '

&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;
}