In PHP, objects that implement Traversable can be used in
Traversable can’t be implemented directly in userland (pure PHP) code and instead Iterator or IteratorAggregate have to be used.
But what if you’re defining an interface that’s iterable as part of its contract? Should your interface extend
Extend Traversable Instead
Neither. Instead interfaces should extend
Since interfaces should be, for the most part, role based the clients of an interface shouldn’t care that
IteratorAggregate is used. They just care that they can iterate over an object.
Extending Traversable means that it’s up to the implementing class to choose the best way to accomplish its iteration. Just like it should be.
Implementing Interfaces that Extend Traversable
To implement an interface that extends traversable, the implementing class’s
implements declaration should include
IteratorAggregate. The trick here is the ordering: Iterator or IteratorAggregate must come first.
Doing otherwise causes an error on PHP (but seems to work okay on HHVM).