php - ArrayAccess 多维(非)集?

标签 php arrays interface multidimensional-array

我有一个实现 ArrayAccess 的类,我正试图让它与多维数组一起工作。 existsget 起作用。 setunset 给我带来了问题。

class ArrayTest implements ArrayAccess {
    private $_arr = array(
        'test' => array(
            'bar' => 1,
            'baz' => 2
        )
    );
    
    public function offsetExists($name) {
        return isset($this->_arr[$name]);
    }
    
    public function offsetSet($name, $value) {
        $this->_arr[$name] = $value;
    }
    
    public function offsetGet($name) {
        return $this->_arr[$name];
    }
    
    public function offsetUnset($name) {
        unset($this->_arr[$name]);
    }
}

$arrTest = new ArrayTest();


isset($arrTest['test']['bar']);  // Returns TRUE

echo $arrTest['test']['baz'];    // Echo's 2

unset($arrTest['test']['bar']);   // Error
$arrTest['test']['bar'] = 5;     // Error

我知道 $_arr 可以公开,这样您就可以直接访问它,但对于我的实现来说,它不是我们想要的,而是私有(private)的。

最后两行抛出错误:注意:间接修改重载元素

我知道 ArrayAccess 通常不适用于多维数组,但是是否有围绕这个或任何稍微干净的实现来实现所需的功能?

我能想到的最好的想法是使用一个字符作为分隔符并在 setunset 中测试它并相应地采取行动。尽管如果您处理的是可变深度,这会变得非常丑陋非常快。

有谁知道为什么 existsget 可以复制功能?

感谢任何人可以提供的帮助。

最佳答案

通过将 public function offsetGet($name) 更改为 public function &offsetGet($name)(通过添加 return通过引用),但是它会导致 fatal error (“ArrayTest::offsetGet() 的声明必须与 ArrayAccess::offsetGet() 的声明兼容”)。

PHP 作者前段时间搞砸了这个类,现在他们 won't change it in sake of backwards compatibility :

We found out that this is not solvable without blowing up the interface and creating a BC or providing an additional interface to support references and thereby creating an internal nightmare - actually i don't see a way we can make that work ever. Thus we decided to enforce the original design and disallow references completley.

编辑:如果您仍然需要该功能,我建议您改用魔术方法(__get()__set()、等),因为 __get() 通过引用返回值。这会将语法更改为如下所示:

$arrTest->test['bar'] = 5;

当然不是理想的解决方案,但我想不出更好的解决方案。

更新:这个问题是fixed in PHP 5.3.4 ArrayAccess 现在按预期工作:

Starting with PHP 5.3.4, the prototype checks were relaxed and it's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of ArrayAccess objects possible.

关于php - ArrayAccess 多维(非)集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2881431/

相关文章:

php - 在 MySQL 中处理多个数组数据的最佳方式?

javascript - PHP Ajax错误,输入第一个字符时得到404

java - 为什么 List 是一个接口(interface)而不是一个类

java - 使用类的对象调用另一个类的方法

java - 搜索从文件中提取的数据,并将其存储到数组中以获取答案。 IO

interface - 你如何在 Rust 中声明一个接口(interface)?

php - 如何使用 asynctask 将图像从 android 上传到 php

php - 如何将空格发送到 MySQL 数据库

java - 用另一个模式替换二维数组中的模式

arrays - 如何在 Swift 中查找列表项的索引?