0
0
PHPprogramming~5 mins

Yield from delegation in PHP

Choose your learning style9 modes available
Introduction

Yield from delegation helps you easily get values from one generator inside another without extra loops.

You want to combine results from multiple generators into one sequence.
You have a generator that calls another generator and want to pass values through.
You want cleaner code when working with nested generators.
You want to pause and resume multiple sequences smoothly.
Syntax
PHP
yield from <generator_expression>;

This passes all yielded values from the inner generator to the outer one.

It simplifies code by avoiding manual loops to yield each value.

Examples
This example shows how yield from passes values from gen1 inside gen2.
PHP
<?php
function gen1() {
    yield 1;
    yield 2;
}

function gen2() {
    yield from gen1();
    yield 3;
}

foreach (gen2() as $value) {
    echo $value . " ";
}
This example combines two generators using yield from to produce letters then numbers.
PHP
<?php
function letters() {
    yield 'a';
    yield 'b';
}

function numbers() {
    yield 1;
    yield 2;
}

function combined() {
    yield from letters();
    yield from numbers();
}

foreach (combined() as $item) {
    echo $item . " ";
}
Sample Program

This program shows how yield from lets outerGenerator include all values from innerGenerator easily.

PHP
<?php
function innerGenerator() {
    yield 'apple';
    yield 'banana';
}

function outerGenerator() {
    yield 'start';
    yield from innerGenerator();
    yield 'end';
}

foreach (outerGenerator() as $fruit) {
    echo $fruit . "\n";
}
OutputSuccess
Important Notes

yield from can delegate to any iterable, not just generators.

It helps keep generator code clean and readable.

Summary

Yield from delegation passes values from one generator to another easily.

It avoids writing loops to yield each value manually.

Use it to combine or chain generators simply.