我正在尝试存储一个数组,并使用扩展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行代码的情况下让它工作呢?
发布于 2012-05-22 22:04:54
这是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;
}
} https://stackoverflow.com/questions/10703443
复制相似问题