PHP interfaces IteratorAggregate vs Iterator?

arrays, iterator, php, traversal

Solution

I assume `IteratorAggregate` is for cases where you want to save time, and `Iterator` is for cases where you need fine control over iteration through your object. For example it lets you add custom exceptions on `next()`, `key()` or `prev()` failures, caching(if you iterate through something that takes data over the network), preprocess values before returning them.

Problem

The `IteratorAggregate` is an interface to create an external Iterator: ``` class myData implements IteratorAggregate { public $property1 = "Public property one"; public $property2 = "Public property two"; public $property3 = "Public property three"; public function __construct() { $this->property4 = "last property"; } public function getIterator() { return new ArrayIterator($this); } } $obj = new myData; ``` And you'll be able to traverse the object using `foreach`: ``` foreach($obj as $key => $value) { var_dump($key, $value); echo "\n"; } ``` While `Iterator` is an interface for external iterators or objects that can be iterated themselves internally: ``` class myIterator implements Iterator { private $position = 0; private $array = array('one', 'two', 'three'); function rewind() { $this->position = 0; } function current() { return $this->array[$this->position]; } function key() { return $this->position; } function next() { ++$this->position; } function valid() { return isset($this->array[$this->position]); } } ``` And again, you can traverse it basically the same way: ``` $it = new myIterator; foreach($it as $key => $value) { var_dump($key, $value); echo "\n"; } ``` So can anyone explain why we need two interfaces and what's the difference between them?

Original source