Array returned by getIterator in PHPs IteratorAggregate not traversable
arrays, class, iterator, php
Solution
You should return an Iterator in getIterator. You can try ArrayIterator.
public function getIterator() {
return new ArrayIterator($this->items);
}
Problem
I am trying to make use of PHPs IteratorAggregate but not having much luck. The object that implements IteratorAggregate has a property $items which is an array of objects My_Object. When the users uses a foreach statement with instances of My_Collection I want it to iterate over the the $items array... However the code below does not appear to be working as expected. ``` 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>" ); } ``` I am getting the following error: ``` <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 /> ``` Any help would be appreciated.