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!

Published by Jamie Todd Rubin

Jamie Todd Rubin writes fiction and nonfiction for a variety of publications including Analog, Clarkesworld, The Daily Beast, 99U, Daily Science Fiction, Lightspeed, InterGalactic Medicine Show, and several anthologies. He was featured in Lifehacker’s How I Work series. He has been blogging since 2005. By day, he manages software projects and occasionally writes code. He lives in Falls Church, Virginia with his wife and three children. Find him on Twitter at @jamietr.