bhylu.com

Advertisements

PHP Generators

A generator supplies values as a caller asks for them. It can make a sequential pipeline use less intermediate memory than constructing an entire array up front.

How it works

A function containing yield returns a Generator. The body advances during iteration rather than completing all work at the initial call. yield from can delegate to another iterable. This does not make a blocking file read asynchronous, and a generator can still retain large objects or other resources. Define ownership and cleanup if iteration may stop early.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l generators.php
php generators.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · generators.php

<?php
declare(strict_types=1);

function dueIds(): iterable {
    yield 41;
    yield from [42, 43];
}
$total = 0;
foreach (dueIds() as $id) { $total += $id; }
echo $total, "\n";

Expected result

126

The caller consumes one ID at a time and keeps only a running total. Delegation provides the same iterable contract for the short list. This small fixture demonstrates laziness, not a benchmark; a real benefit depends on the size of the source and what each stage retains.

Check the official PHP manual for detailed version and API contracts.