gpt4 book ai didi

php - PHPs IteratorAggregate 中 getIterator 返回的数组不可遍历

转载 作者:可可西里 更新时间:2023-11-01 00:32:38 24 4
gpt4 key购买 nike

我正在尝试使用 PHP 的 IteratorAggregate,但运气不佳。实现 IteratorAggregate 的对象有一个属性 $items,它是一个对象数组 My_Object。

当用户使用带有 My_Collection 实例的 foreach 语句时,我希望它遍历 $items 数组...但是下面的代码似乎没有按预期工作。

class My_Object {

public $value;

public function __construct( $value ) {
$this->value = $value;
}

}

class My_Collection implements IteratorAggregate {

protected $items = array();

public function add_item( $value ) {
array_push( $this->items, new My_Object( $value ) );
}

public function getIterator() {
return $this->items;
}
}

$my_collection = new My_Collection();
$my_collection->add_item( 1 );
$my_collection->add_item( 2 );
$my_collection->add_item( 3 );

foreach( $my_collection as $mine ) {
echo( "<p>$mine->value</p>" );
}

我收到以下错误:

<b>Fatal error</b>:  Uncaught exception 'Exception' with message 'Objects returned by My_Collection::getIterator() must be traversable or implement interface Iterator' in [...][...]:29
Stack trace:
#0 [...][...](29): unknown()
#1 {main}
thrown in <b>[...][...]</b> on line <b>29</b><br />

如有任何帮助,我们将不胜感激。

最佳答案

您应该在 getIterator 中返回一个 Iterator。你可以试试 ArrayIterator。

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

关于php - PHPs IteratorAggregate 中 getIterator 返回的数组不可遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444924/

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