← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Generators & yield (PHP 5.5)

php PHP 5.5+ Intermediate
debt(d7/e3/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7), because the detection_hints note automated=no and the code_pattern targets file() or fetchAll() calls — phpstan can flag these patterns but won't reliably identify every missed generator opportunity. The absence of a generator is a sins-of-omission problem: no error is thrown, no warning fires by default, and memory exhaustion only surfaces at runtime with large datasets.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3), because the quick_fix describes replacing array-returning functions with generator functions using yield — a contained refactor within one function or component. It's more than a one-line swap (callers must tolerate a Generator instead of an array, and foreach loops replace array operations), but it typically stays within a single file or small component.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), because the choice to use or not use generators is scoped to specific data-loading functions. Once adopted, callers need to use foreach/iterator patterns rather than array functions, imposing a small but localised tax. The rest of the codebase is largely unaffected unless the pattern is used pervasively.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5), because the misconception field explicitly states that developers treat generators as 'syntax sugar for arrays' when they are fundamentally different (lazy evaluation, constant memory, forward-only, non-rewindable). The common mistakes confirm this: developers load large data into arrays instead of yielding, and are surprised that generators cannot be rewound. This is a documented gotcha that most PHP devs eventually learn.

About DEBT scoring →

TL;DR

Generators (PHP 5.5) use yield to produce values lazily — enabling memory-efficient iteration over large datasets without loading everything into memory.

Explanation

A generator function uses yield instead of return. Calling the function returns a Generator object (implements Iterator). Values are computed on demand. yield $value; pauses the function, returning the value. Execution resumes on next iteration. yield $key => $value; for key-value pairs. yield from iterable; delegates to another generator. send($value) passes a value back into the generator. Generators use O(1) memory regardless of dataset size — vs O(n) for arrays. Use cases: reading large files line by line, database cursors, infinite sequences, lazy pipelines.

Common Misconception

Generators are just syntax sugar for arrays — generators are fundamentally different: they compute values lazily, use constant memory, and can represent infinite sequences.

Why It Matters

Generators enable processing of datasets larger than available memory — a 10GB CSV that would crash with file() can be processed line-by-line with a generator.

Common Mistakes

  • Not using generators for large file/database iteration — loading into array instead.
  • Not knowing yield from can delegate to sub-generators.
  • Trying to rewind a generator — they're forward-only by default.

Code Examples

✗ Vulnerable
// Memory issue — loads everything:
function readCsv(string $file): array {
    return file($file); // Fatal on large files
}
✓ Fixed
// Constant memory — O(1):
function readCsvLines(string $file): Generator {
    $handle = fopen($file, 'r');
    while (($line = fgetcsv($handle)) !== false) {
        yield $line;
    }
    fclose($handle);
}

foreach (readCsvLines('huge.csv') as $row) {
    processRow($row);
}

Added 23 Mar 2026
Views 29
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 1 ping W 0 pings T 0 pings F
No pings yet today
No pings yesterday
Amazonbot 7 Perplexity 6 ChatGPT 3 Unknown AI 3 Google 2 Ahrefs 1
crawler 21 pre-tracking 1
DEV INTEL Tools & Severity
🔵 Info ⚙ Fix effort: Medium
⚡ Quick Fix
Replace array-returning functions over large data with generators. Use yield for each item. File reading: yield from fgetcsv loop. DB: yield from cursor.
📦 Applies To
PHP 5.5+ web cli queue-worker
🔗 Prerequisites
🔍 Detection Hints
file\(|fetchAll\(
Auto-detectable: ✗ No phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update
CWE-400

✓ schema.org compliant