编辑:我意识到文字的数量可能令人生畏。这个问题的本质:
如何以一种使设置多维值成为可能的方式实现 ArrayAccess?
我知道这已经在这里讨论过,但我似乎无法正确实现 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 文档也不是很有帮助。
要直接复制它(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 库,该库在 MIT 许可下在Githublibconfig
上可用。