What is the IteratorAggregate interface, and how does it provide a simpler alternative to implementing the full Iterator interface directly?
Short answer
The IteratorAggregate interface requires implementing just a single method, getIterator, which returns an object that itself implements Iterator, often conveniently a generator or an ArrayIterator wrapping an internal array, letting you make a class iterable without needing to…
Advertisement
AModel answer
The IteratorAggregate interface requires implementing just a single method, getIterator, which returns an object that itself implements Iterator, often conveniently a generator or an ArrayIterator wrapping an internal array, letting you make a class iterable without needing to manually implement all five of the Iterator interface's individual methods yourself, significantly reducing boilerplate for the common case of simply wrapping an existing collection of data.
class NumberCollection implements IteratorAggregate {
private $items = [1, 2, 3];
public function getIterator(): Iterator {
return new ArrayIterator($this->items);
}
}Real-world example
A developer building a custom collection class chooses IteratorAggregate over the full Iterator interface, writing a single simple method that delegates to a built in ArrayIterator rather than manually implementing five separate iteration methods.
Likely follow-ups
- When would you choose to implement Iterator directly instead of using IteratorAggregate?
- Can getIterator return a generator instead of an ArrayIterator?
Related topics