php · level 3 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A hands out values one at a time, pausing in between.
A function that returns an array must build all of it first. A million rows means a million rows held at once. A generator is instead: each hands out one value and pauses the function right there, until the loop asks for the next.
Write yield instead of return and PHP turns the function into a generator. Calling it runs nothing yet. It hands back a Generator object, and foreach pulls the values out one by one. That makes it perfect for reading a big file line by line with fopen and fgets.
<?php
function lines(string $path): Generator {
$file = fopen($path, "r");
$line = fgets($file);
while ($line !== false) {
yield trim($line);
$line = fgets($file);
}
fclose($file);
}
$path = sys_get_temp_dir() . "/shopping.txt";
file_put_contents($path, "milk\neggs\nbread\n");
foreach (lines($path) as $item) {
echo "Buy $item\n";
} fopen opens the file for reading, fgets reads one line or gives false at the end, and fclose closes it.
guess first
When does the countdown really start? Make a guess.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function countdown(): Generator {
echo "Starting\n";
yield 3;
yield 2;
echo "Almost\n";
yield 1;
}
$numbers = countdown();
echo "Ready?\n";
foreach ($numbers as $n) {
echo "$n\n";
}
your turn
Your turn. Hand out deli tickets.
Type the keyword that hands a value out of a generator. Then choose a counter name, like DELI, and how many tickets to print.
fix it
Only one reading comes out, and then it crashes. Fix it.
- The
TypeErrorsays the function promised aGeneratorbut returned a string. Which word on line 4 ends the function? returnhands back one value and stops for good. A generator hands out many values and pauses between them.- On line 4, change
returntoyield, then run it.
nailed it
your functions can pause and carry on. :D
yieldhands out one value, then pauses the function.- A generator is lazy: values are made only when asked for.
- Loop over a generator with
foreach, the same way as an array.
new words in your collection
- generator
- yield
- lazy
This lesson isn’t saved. A free account remembers every lesson you finish.