gpt4 book ai didi

php - 无法向 IteratorAggregate 写入新元素?

转载 作者:行者123 更新时间:2023-12-02 07:13:16 24 4
gpt4 key购买 nike

我认为 IteratorAggregate 仅提供对对象的类数组读取 访问是否正确?如果我需要写入对象数组,那么我需要使用 Iterator 吗?

尝试添加新元素时 IteratorAggregate 对象导致 fatal error 的演示如下:

<?

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

最佳答案

对于它的值(value),给定您的示例类,您可以使用 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

关于php - 无法向 IteratorAggregate 写入新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3585164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com