Generators
function rangeGenerator(int \$start, int \$end): Generator {
for (\$i = \$start; \$i <= \$end; \$i++) {
yield \$i;
}
}
foreach (rangeGenerator(1, 5) as \$num) {
echo \$num; // 1 2 3 4 5
}
Key-Value Yield
function mapGenerator(array \$items): Generator {
foreach (\$items as \$key => \$value) {
yield \$key => strtoupper(\$value);
}
}
Generator Delegation
function gen1(): Generator {
yield 1;
yield 2;
yield from [3, 4, 5]; // delegate
yield from gen2(); // delegate to another generator
}
IteratorAggregate
class MyCollection implements IteratorAggregate {
public function __construct(private array \$items) {}
public function getIterator(): Traversable {
return new ArrayIterator(\$this->items);
}
}