Helpful tip for anyone trying to build collection objects in PHP using the IteratorAggregate

If anyone out there is trying to build a collection object in PHP using the IteratorAggregate, here’s a tip that will save you hours of debugging and online searching:

Return an ArrayObject from getIterator()!

What finally worked for me looks something like this:

class Collection implements IteratorAggregate
{
private $items = array();
private $count = 0;

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

public function add($value)
{
$this->items[$this->count++] = $value;
}

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

All of the documentation I could find online seemed to indicate that the object returned from getIterator() should be the class itself (e.g. Collection), but that didn’t work. So through some searching and a lot of trial and error, I finally figured it out. And it only took me a couple of hours to figure that out!

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.