Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

IteratorAggregate

IteratorAggregate is an interface to create a custom iterator.

It requires a single method, that returns an iterator that will be used with PHP native functions.

It also suggest that several iterators may be merged in one, by creating a class that merges them.

<?php

    declare(strict_types=1);
    
    class MergedIteratorAggregate implements IteratorAggregate
    {
        /** @var iterable[] */
        private array $iterables = [];
    
        public function addIterable(iterable $iterable): void
        {
            $this->iterables[] = $iterable;
        }
    
        public function getIterator(): Traversable
        {
            foreach ($this->iterables as $iterable) {
                // yield from works with arrays AND Traversable objects
                yield from $iterable;
            }
        }
    }
    
    $aggregate = new MergedIteratorAggregate();

    function diceRoll() {
        yield rand(0, 10);

    }

    // Using iterator with generators
    $aggregate->addIterable(diceRoll());
    $aggregate->addIterable(diceRoll());
    foreach($aggregate as $value) {
        print $value.PHP_EOL;
    }

?>

Documentation

See Also