The Yield Keyword

suggest change

A yield statement is similar to a return statement, except that instead of stopping execution of the function and returning, yield instead returns a Generator object and pauses execution of the generator function.

Here is an example of the range function, written as a generator:

function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

You can see that this function returns a Generator object by inspecting the output of var_dump:

var_dump(gen_one_to_three())

# Outputs:
class Generator (0) {
}

Yielding Values

The Generator object can then be iterated over like an array.

foreach (gen_one_to_three() as $value) {
    echo "$value\n";
}

The above example will output:

1
2
3

Yielding Values with Keys

In addition to yielding values, you can also yield key/value pairs.

function gen_one_to_three() {
    $keys = ["first", "second", "third"];

    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $keys[$i - 1] => $i;
    }
}

foreach (gen_one_to_three() as $key => $value) {
    echo "$key: $value\n";
}

The above example will output:

first: 1
second: 2
third: 3

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents