What are PHP generators?
Why Interviewers Ask This
This tests whether you can apply PHP knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
Generators (PHP 5.5+) provide a simple, memory-efficient way to implement iterators without needing to build a full Iterator class. A generator function uses the yield keyword to produce values one at a time, pausing execution between each yield. Unlike returning an array (which builds everything in memory), a generator produces each value on demand: function fibonacci() { [$a, $b] = [0, 1]; while(true) { yield $a; [$a, $b] = [$b, $a + $b]; } }. This enables infinite sequences with no memory issues. yield from delegates to another generator. Generators return a Generator object, which implements the Iterator interface, so they work directly in foreach loops.
Pro Tip
This topic has PHP-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.