【问题标题】:Using ArrayObject to store arrays使用 ArrayObject 存储数组
【发布时间】:2012-05-22 13:50:52
【问题描述】:

我正在尝试存储一个数组并使用扩展 ArrayObject 的自定义类来操作该数组。

class MyArrayObject extends ArrayObject {
    protected $data = array();

    public function offsetGet($name) {
        return $this->data[$name];
    }

    public function offsetSet($name, $value) {
        $this->data[$name] = $value;
    }

    public function offsetExists($name) {
        return isset($this->data[$name]);
    }

    public function offsetUnset($name) {
        unset($this->data[$name]);
    }
}

问题是如果我这样做:

$foo = new MyArrayObject();
$foo['blah'] = array('name' => 'bob');
$foo['blah']['name'] = 'fred';
echo $foo['blah']['name'];

输出是 bob 而不是 fred。有什么方法可以在不更改上述 4 行的情况下使其工作?

【问题讨论】:

    标签: php arrays arrayobject


    【解决方案1】:

    这是 ArrayAccess 的一个已知行为(“PHP 注意:间接修改 MyArrayObject 的重载元素无效”...)。

    http://php.net/manual/en/class.arrayaccess.php

    在 MyArrayObject 中实现这个:

    public function offsetSet($offset, $data) {
        if (is_array($data)) $data = new self($data);
        if ($offset === null) {
            $this->data[] = $data;
        } else {
            $this->data[$offset] = $data;
        }
    } 
    

    【讨论】:

    • 问题是数组被存储为对象,所以如果我设置一个值数组,我必须在循环之前调用toArray()
    • @fire 实现迭代器和可数也许?
    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多