PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Iterator or IteratorAggregate?

Note: This article was originally published at Planet PHP on 25 June 2010.
Planet PHP

In my last two posts, I talked about PHP iterators. Here is a quick tip on the same topic.

If you have ever used iterators in your code, you have probably implemented the Iterator interface. Objects of a class that implements Iterator can be iterated over with the foreach loop:

$foo = new Foo(); A foreach ($foo as $key = $value) { // do something with $key and $value } A

The Iterator interface has five simple methods that must be implemented:

class Foo implements Iterator { protected $attributes; A public function rewind() { reset($this-attributes); } A public function current() { return current($this-attributes); } A public function key() { return key($this-attributes); } A public function next() { return next($this-attributes); } A public function valid() { return false !== current($this-attributes); } } A

The IteratorAggregate interface is quite similar (both interfaces implement Traversable) but creates an external Iterator. But when the iterator is based on an array, creating an external Iterator for this array gives you a more concise and more readable code:

class Foo implements IteratorAggregate { protected $attributes; A public function getIterator() { return new ArrayIterator($this-attributes); } } A