3

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.

1
  • Did you try foreach($my_collection->getIterator() as $mine) ? Commented Jan 29, 2014 at 23:30

1 Answer 1

7

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

public function getIterator() {
    return new ArrayIterator($this->items);
}
Sign up to request clarification or add additional context in comments.

3 Comments

According to this blog entry jeremycook.ca/2012/05/06/… "…it’s up to you whether this is an array or an object that implements the Traversable interface." And the example shows use of an array.
Please see the topmost comment here: php.net/iteratoraggregate "Note that, at least as of 5.3, you still aren't allowed to return a normal Array from getIterator()." I'm not sure what PHP version you're using but I haven't seen the change that allows arrays.
Ok cool. Well your solution worked and I will check my version too. Thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.