Requirement PHP 5.5+
- Generators are simple iterators.
- Compute and yield iteration values on-demand without commandeering valuable memory.
- Iterate in only one direction—forward
- Can’t iterate the same generator more than once
Create generator
1 2 3 4 5 6 7 8 9 10
| <?php function myGenerator() { yield 'value1'; yield 'value2'; yield 'value3'; }
foreach (myGenerator() as $yieldedValue) { echo $yieldedValue, PHP_EOL; }
|
Output:
Use generator
Bad to use traditional iterator because it load everything into memory.
1 2 3 4 5 6 7 8 9 10 11 12
| <?php function makeRange($length) { $dataset = []; for ($i = 0; $i < $length; $i++) { $dataset[] = $i; } return $dataset; } $customRange = makeRange(1000000); foreach ($customRange as $i) { echo $i, PHP_EOL; }
|
Good to use generator.
1 2 3 4 5 6 7 8 9
| <?php function makeRange($length) { for ($i = 0; $i < $length; $i++) { yield $i; } } foreach (makeRange(1000000) as $i) { echo $i, PHP_EOL; }
|
CSV generator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php function getRows($file) { $handle = fopen($file, 'rb'); if ($handle === false) { throw new Exception(); } while (feof($handle) === false) { yield fgetcsv($handle); } fclose($handle); } foreach (getRows('data.csv') as $row) { print_r($row); }
|