๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Generators

A generator is a function that pauses and hands out values one at a time. The word yield marks each pause point.

A generator yields three values

The function yields 10, then 20, then 30. The foreach loop prints each value as it arrives.

<?php
function numbers() {
  yield 10;
  yield 20;
  yield 30;
}
foreach (numbers() as $n) {
  echo $n, "\n";
}

Nothing runs until the walk advances

Making the generator runs none of its body. Each step line prints only when the walk reaches that yield.

<?php
function steps() {
  echo "step one\n";
  yield 1;
  echo "step two\n";
  yield 2;
}
echo "before\n";
$gen = steps();
echo "created\n";
foreach ($gen as $n) {
  echo $n, "\n";
}

Keyed yields carry a name with each value

Each yield names its value with a key before the arrow. The foreach loop reads the key and the value together.

<?php
function labels() {
  yield "a" => 1;
  yield "b" => 2;
}
foreach (labels() as $k => $v) {
  echo $k, "=", $v, "\n";
}

Example

<?php
function countdown() {
  yield 3;
  yield 2;
  yield 1;
}
foreach (countdown() as $n) {
  echo $n, "\n";
}

Key points

  • Calling a generator function returns a Generator object instead of running the body.
  • Each yield hands out one value and pauses the function at that line.
  • A foreach loop resumes the generator again and again until it ends.
  • Values are made one at a time, only when the walk asks for the next one.
  • A yield can carry a key with its value, written with an arrow between them.

In this example, countdown yields 3 first and pauses there. The foreach loop prints 3 and resumes the function. The same pause and print repeats for 2 and for 1.

Note

A generator keeps its place between yields, so its local variables survive each pause.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does the code after a yield line run?