我正在尝试存储一个数组并使用扩展 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'];
输出是鲍勃而不是弗雷德。有什么方法可以在不更改上述 4 行的情况下使其工作?
这是
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;
}
}