PHP: Traversable interface
What is Traversable?
Traversable is a built-in PHP interface that marks a class as iterable – meaning it can be traversed using a foreach loop.
Its implementation doesn’t have any methods:
interface Traversable {}
How is it used in practice?
You can’t implement the Traversable interface yourself. Doing so will result in a fatal error. Its sole purpose is to tell PHP that the class is traversable.
Instead, you’ll typically implement the Iterator or IteratorAggregate interfaces which in turn extend Traversable.
Iterator
You can implement Iterator if you want to define a custom iterator logic yourself.
interface Iterator extends Traversable
{
public function current(): mixed;
public function key(): mixed;
public function next(): void;
public function rewind(): void;
public function valid(): bool;
}
IteratorAggregate
You can implement IteratorAggregate if you want to delegate iteratior to another object that is itself Traversable
interface IteratorAggregate extends Traversable
{
public function getIterator(): Traversable;
}
If your class implements one of the above interfaces, it automatically becomes Traversable too so you can iterate over it using a foreach:
class MyCollection implements IteratorAggregate
{
private array $items = ['a', 'b', 'c'];
public function getIterator(): Traversable
{
return new ArrayIterator($this->items);
}
}
$collection = new MyCollection();
foreach ($collection as $item) {
echo $item; // a, b, c
}