Чем генераторы отличаются от итераторов?

Ответ

Генератор - упрощенный итератор, создаваемый функцией с yield. Не нужно реализовывать 5 методов Iterator.

// Итератор - много boilerplate
class RangeIterator implements Iterator {
    private int $current;
    public function __construct(private int $start, private int $end) {
        $this->current = $start;
    }
    public function current(): int { return $this->current; }
    public function key(): int { return $this->current - $this->start; }
    public function next(): void { $this->current++; }
    public function rewind(): void { $this->current = $this->start; }
    public function valid(): bool { return $this->current <= $this->end; }
}

// Генератор - 3 строки
function range_gen(int $start, int $end): Generator {
    for ($i = $start; $i <= $end; $i++) { yield $i; }
}

Генераторы нельзя перемотать назад (rewind), итераторы - можно (если реализовано).

🧠Квиз 🏆Лидеры 🎯Собесед. 📖Вопросы 📚База зн.