无法将新元素写入IteratorAggregate?

时间:2010-08-27 14:31:27

标签: php arrays iterator spl

我是否认为IteratorAggregate仅提供对象的类似数组的读取访问权限?如果我需要写入object-as-array,那么我需要使用Iterator

在尝试添加新元素时演示导致致命错误的IteratorAggregate对象如下:

<?

class foo implements IteratorAggregate {

    public $_array = array('foo'=>'bar', 'baz'=>'quux');

    public function getIterator() {
        return new ArrayIterator($this->_array);
    }

} // end class declaration


$objFoo = & new foo();

foreach ( $objFoo as $key => $value ) {
        echo "key: $key, value: $value\n";
}

$objFoo['reeb'] = "roob";

foreach ( $objFoo as $key => $value ) {
        echo "key: $key, value: $value\n";
}

$ php test.php
key: foo, value: bar
key: baz, value: quux

Fatal error: Cannot use object of type foo as array in /var/www/test.php on line 20

Call Stack:
    0.0009      57956   1. {main}() /var/www/test.php:0

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:4)

考虑到你的样本课,你可以使用ArrayObject(我们想要实现IteratorAggregateArrayAccess)。

class Foo extends ArrayObject
{
    public function __construct()
    {
        parent::__construct(array('foo' => 'bar', 'baz' => 'quux'));
    }
}

$objFoo = new Foo();

foreach ( $objFoo as $key => $value ) {
    echo "$key => $value\n";
}

echo PHP_EOL;

$objFoo['foo'] = 'badger';
$objFoo['baz'] = 'badger';
$objFoo['bar'] = 'badger';

foreach ( $objFoo as $key => $value ) {
    echo "$key => $value\n";
}

输出正如预期的那样:

foo => bar
baz => quux

foo => badger
baz => badger
bar => badger