WeCodeAcademy

PHP Closures and Generators

ExamplePHP
<?php
$greeting = "Hello";
$greet = function ($name) use ($greeting) {
  return "$greeting, $name!";
};
echo $greet("Ada"), "\n";

function counter(): Closure {
  $n = 0;
  return function () use (&$n) { return ++$n; };
}
$c = counter();
echo $c(), $c(), $c(), "\n";

function squares(int $max) {
  for ($i = 1; $i <= $max; $i++) {
    yield $i => $i * $i;
  }
}
foreach (squares(4) as $n => $sq) {
  echo "$n squared is $sq\n";
}

$compose = fn(callable ...$fns) => fn($x) => array_reduce($fns, fn($acc, $f) => $f($acc), $x);
echo $compose(fn($x) => $x + 1, fn($x) => $x * 10)(4), "\n";
Output
Hello, Ada!
123
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
50

A generator (yield) produces values one at a time, so it can describe a huge sequence without storing it all in memory.

Quick check

What does yield do in a function?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.