CKTIS / PHP
IteratorAggregate::getIterator — delegate iteration in `foreach`
Implement `getIterator()` to control which keys and values `foreach` reads from an object. The method supplies a `Traversable` object, not an array.
Version: PHP 8.3
Syntax
public function getIterator(): \TraversableIn PHP 8.3, IteratorAggregate::getIterator is a public instance method with no parameters. When foreach starts iterating over an object that implements IteratorAggregate, it calls this method and takes the keys and values from the returned object. Unlike a class implementing Iterator, the collection does not have to track the current position itself.
The interface's \Traversable return type is tentative in PHP 8.3. An implementation can declare : \Traversable as in the example, or a compatible narrower return type (covariance), such as : \Generator. The method can return a \ArrayIterator, for example, or use yield to supply elements through a \Generator. An array is not a Traversable object, even though foreach can loop over arrays and the iterable type accepts them. Returning an array with the declared \Traversable type causes a TypeError.
No optional extension is required: IteratorAggregate, Traversable, and generators are built in, and ArrayIterator is part of the mandatory SPL extension.
If the collection should support repeated or nested passes, create a fresh iterator on each call. Returning the same generator can prevent a later pass: a generator cannot rewind once it has advanced past its first yield.
Examples
<?php
final class ColorPalette implements \IteratorAggregate
{
public function getIterator(): \Traversable
{
yield 'primary' => 'blue';
yield 'accent' => 'orange';
}
}
$palette = new ColorPalette();
for ($pass = 1; $pass <= 2; $pass++) {
echo "Pass {$pass}:\n";
foreach ($palette as $role => $color) {
echo "{$role} = {$color}\n";
}
}
Result
Pass 1: primary = blue accent = orange Pass 2: primary = blue accent = orange
Both passes use the same palette. Each `foreach` gets a fresh generator, so it prints the same two key-value pairs in the same order.
Related lessons
- PHP · Lesson 62 · Advanced · Version: 2