McShaman
McShaman

Reputation: 3995

Array returned by getIterator in PHPs IteratorAggregate not traversable

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.

Upvotes: 3

Views: 4258

Answers (1)

Buga D&#225;niel
Buga D&#225;niel

Reputation: 830

You should return an Iterator in getIterator. You can try ArrayIterator.

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

Upvotes: 7

Related Questions