我正在尝试使用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);
}