PHP / CHAPTER 12
Generators and bounded memory
AdvancedStream work while keeping execution and resource lifetimes clear.
By the end of this chapter
- Explain yield-driven execution
- Avoid eager materialization of large sources
- Release resources through finally during generator cleanup
The idea
A function containing yield returns a Generator that produces values as the consumer iterates. This can avoid building a large intermediate array when each item can be processed independently. The function body runs during iteration, so parsing errors and side effects may occur later than the call that created the generator. Keep that timing visible in the API contract.
Streaming does not automatically bound memory if later code stores every result or converts the generator into an array. Consider the entire pipeline and stop when enough output has been collected. If a generator owns a resource, arrange cleanup with try and finally and ensure the generator is eventually exhausted or released; keeping a suspended generator referenced can keep its resource open. Treat consumption and lifetime as separate responsibilities.
<?php
function positive(array $values): Generator {
foreach ($values as $value) {
if ($value > 0) yield $value;
}
}
foreach (positive([-2, 3, 0, 5]) as $value) {
echo $value, "
";
}3 5
The generator yields matching values one at a time. This example’s input is already an array, so its benefit is avoiding a second result array.
Try it yourself
Create a generator that yields nonblank normalized lines from an iterable without collecting all results.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING