PHP generators provide a powerful way to work with large datasets without consuming excessive memory. Unlike traditional arrays, generators yield values one at a time.

Basic Generator Example

function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

foreach (xrange(1, 1000000) as $number) {
    echo $number . "\n";
}

Key Benefits

  • Memory efficiency: Only one value exists in memory at a time
  • Lazy evaluation: Values are generated only when needed
  • Simplified code: No need to implement Iterator interface

Advanced Techniques

1. Sending Values to Generators

function logger() {
    while (true) {
        $message = yield;
        echo date('[Y-m-d H:i:s] ') . $message . "\n";
    }
}

$log = logger();
$log->send('User logged in');
$log->send('Data processed');

2. Generator Delegation

function countToTen() {
    yield from [1, 2, 3];
    yield from fourToSeven();
    yield from [8, 9, 10];
}

function fourToSeven() {
    for ($i = 4; $i <= 7; $i++) {
        yield $i;
    }
}

Generators are particularly useful for processing large files, database results, or API responses where memory conservation is critical.

By Admin

Leave a Reply

Your email address will not be published. Required fields are marked *