Interview frequency: …
Short answer
A Generator function returns an Iterator without storing all the data in memory; it yields each value and pauses until the next item is requested.
Explanation
Trying to read a 1GB file into an array with a million records can exceed memory_limit immediately. With Generators, the function produces one value per iteration and pauses, keeping memory use very small and stable (a few kilobytes) regardless of the total dataset size.
Code example
function readLargeFile(string $path): Generator {
$handle = fopen($path, 'r');
while (($line = fgets($handle)) !== false) {
yield trim($line);
}
fclose($handle);
}
foreach (readLargeFile("large.txt") as $line) {
// Process line by line
}Common mistakes
- Trying to call count() on a Generator function, which has no predetermined fixed length.