【发布时间】:2015-06-10 03:35:43
【问题描述】:
编辑:我意识到文字的数量可能令人生畏。这个问题的本质是:
如何实现 ArrayAccess 使得设置多维值成为可能?
我知道 here 已经讨论过这个问题,但我似乎无法正确实现 ArrayAccess 接口。
基本上,我有一个类来处理带有数组的应用程序配置并实现ArrayAccess。检索值工作正常,即使是来自嵌套键的值 ($port = $config['app']['port'];)。但是,设置值仅适用于一维数组:一旦我尝试(取消)设置一个值(例如上一个示例中的端口),我就会收到以下错误消息:
Notice: Indirect modification of overloaded element <object name> has no effect in <file> on <line>
现在普遍的看法似乎是offsetGet() 方法必须通过引用返回(&offsetGet())。但是,这并不能解决问题,恐怕我不知道如何正确实现该方法-为什么要使用 getter 方法来设置值? php doc here 也不是很有帮助。
要直接复制这个(PHP 5.4-5.6),请在下面找到示例代码:
<?php
class Config implements \ArrayAccess
{
private $data = array();
public function __construct($data)
{
$this->data = $data;
}
/**
* ArrayAccess Interface
*
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
public function &offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
}
$conf = new Config(array('a' => 'foo', 'b' => 'bar', 'c' => array('sub' => 'baz')));
$conf['c']['sub'] = 'notbaz';
编辑 2: 正如 Ryan 指出的那样,解决方案是改用 ArrayObject(它已经实现了 ArrayAccess、Countable 和 IteratorAggregate)。
要将其应用于包含数组的类,请按如下方式构造它:
<?php
class Config extends \ArrayObject
{
private $data = array();
public function __construct($data)
{
$this->data = $data;
parent::__construct($this->data);
}
/**
* Iterator Interface
*
*/
public function getIterator() {
return new \ArrayIterator($this->data);
}
/**
* Count Interface
*
*/
public function count()
{
return count($this->data);
}
}
我将它用于我的 Config 库 libconfig,它在 MIT 许可下可在 Github 上使用。
【问题讨论】:
标签: php arrays multidimensional-array arrayaccess