In this chapter
We'll learn the never return type for functions that must stop the program, generator functions that yield values one at a time instead of building a whole array, and the habits of good function design — one job, a clear name, few parameters, no hidden output or state — while reviewing the price code before launch.
The Problem in Real Life
Before launch, Marcus asks Mia to review the price code. Yesterday the mobile app sent the service name "hairkut". The price function called unknownService("hairkut"), which printed "Unknown service" — and then the function carried on, found no price, and returned 0. The booking went through for £0.00.
unknownService() was meant to stop the booking. It just didn't. And the old priceDetails() function next to it is 60 lines long, takes six parameters, prints, and reads a global.
The function is called unknownService. How was anyone supposed to know it doesn't actually stop anything?
Mia
A Function That Works vs. a Function You Can Trust
A stop that didn't stop
A function meant to end the request printed a message and returned. The return type never makes PHP check it.
Too much at once
60 lines, six parameters, printing, a global: a function that does everything can't be reused or tested.
One at a time
A generator hands out values one by one, so a year of slots doesn't have to fit in memory at once.
Generators, never and Good Function Design
Finishing touches: the last chapter of the Act covers two special kinds of function and the habits that make all functions easy to trust:
- never: for functions that must not return.
- Generators: functions that
yieldvalues one at a time. - Function design: one job, a clear name, few parameters, no hidden effects.
The never return type: Act 04 introduced never; here's where it earns its place. function unknownService(string $service): never promises that the function never returns to its caller: it always throws an exception (Act 14) or exits. PHP checks the promise. If the function reaches its end normally, as Mia's did after printing, PHP throws a TypeError instead of letting the code carry on. With never, the "hairkut" booking would have stopped. Static analysis tools like PHPStan (Act 21) also understand that the code after a never call can't run.
<?phpdeclare(strict_types=1);function unknownService(string $service): never{echo "Unknown service: $service\n";// forgot to stop here — with never, PHP won't let the function return}function servicePrice(string $service): int{$prices = ["haircut" => 2500, "beard-trim" => 1000];if (!isset($prices[$service])) {unknownService($service);}return $prices[$service];}servicePrice("hairkut");// Unknown service: hairkut// Fatal error: Uncaught TypeError: unknownService(): never-returning function must not implicitly return
<?phpdeclare(strict_types=1);function unknownService(string $service): never{throw new InvalidArgumentException("Unknown service: $service"); // exceptions: Act 14}function servicePrice(string $service): int{$prices = ["haircut" => 2500, "beard-trim" => 1000];if (!isset($prices[$service])) {unknownService($service);}return $prices[$service];}echo servicePrice("haircut"), "\n"; // 2500try {servicePrice("hairkut");} catch (InvalidArgumentException $e) {echo "Booking stopped: ", $e->getMessage(), "\n"; // Booking stopped: Unknown service: hairkut}
Generators: a function that contains yield is a generator. Calling it doesn't run the body; it returns a Generator object, and each round of a foreach over it runs the function up to the next yield, takes that value, and pauses there. So function slots(int $from, int $to) with yield $m; inside a loop hands out one slot at a time. A month of slots for three barbers never sits in memory as one huge array. A generator can also yield $key => $value. You can only go through a generator once, and you can't count it without running it. Act 23 covers generators fully, for files and database results too big for memory.
<?phpdeclare(strict_types=1);function slots(int $fromMinutes, int $toMinutes, int $step = 30): Generator{for ($m = $fromMinutes; $m < $toMinutes; $m += $step) {yield sprintf("%d:%02d", intdiv($m, 60), $m % 60); // pause here, hand out one value}}foreach (slots(9 * 60, 11 * 60) as $slot) {echo $slot, " ";}echo "\n";// 9:00 9:30 10:00 10:30$gen = slots(9 * 60, 18 * 60);var_dump($gen instanceof Generator); // bool(true): the body hasn't run yetecho $gen->current(), "\n"; // 9:00: runs up to the first yield
One job, and a name that says it: a good function does one thing, and its name says what: calculatePrice(), formatPrice(), withHolidaySurcharge(). If the honest name has an "and" in it — calculateAndPrintAndLog() — it's several functions. Short functions are easier to read, test and reuse; a function that doesn't fit on one screen is usually hiding a second one. The guard clauses from Act 06 keep the body flat.
Pure functions: a pure function gets everything through its parameters and gives everything back through return: no echo, no global, no reference parameters, no static memory. Called twice with the same arguments, it gives the same answer and changes nothing else. Pure functions are the easiest code there is to test (Act 21) and to reuse. Keep the calculation pure, and do the printing, saving and sending at the edges of your program.
<?phpdeclare(strict_types=1);// Before: calculates, prints and reads a global — hard to reuse or test$holidayRate = 10;function priceDetails(int $base, int $addOns, bool $isHoliday): void{global $holidayRate;$total = $base + $addOns;if ($isHoliday) {$total += intdiv($total * $holidayRate, 100);}echo "Total: £" . number_format($total / 100, 2) . "\n";}priceDetails(2500, 250, true); // Total: £30.25// After: small, pure, typed — and the printing happens at the edgeconst HOLIDAY_SURCHARGE_PERCENT = 10;function withHolidaySurcharge(int $pence, int $ratePercent = HOLIDAY_SURCHARGE_PERCENT): int{return $pence + intdiv($pence * $ratePercent, 100);}function formatPrice(int $pence): string{return "£" . number_format($pence / 100, 2);}echo "Total: ", formatPrice(withHolidaySurcharge(2500 + 250)), "\n"; // Total: £30.25
Parameters and types: keep the number of parameters small — three or four at most. Instead of boolean flags, prefer separate functions or named arguments (chapter 3); when many values belong together, pass one array or, better, one object (Act 11). Type every parameter and return value, and add a short doc comment for what types can't say: /** @param list<string> $addOns service keys, e.g. "hot-towel" */. The table below is a checklist for every function you write.
| Question | Good sign | Warning sign |
|---|---|---|
| Does it do one job? | The name is one verb phrase | The honest name has "and" in it |
| How long is it? | Fits on one screen | Scrolling, nested ifs, comments marking sections |
| How many parameters? | Three or four, typed | Six, or several booleans |
| Where do values come from? | Parameters and constants | global, static, a variable from the file |
| What does it give back? | A typed return value | echo inside, or changes through & |
| Does it stop the program? | Declared : never and throws | Prints a message and returns |
Key Takeaway
never declares that a function must not return — it has to throw or exit, and PHP enforces it. A generator yields values one at a time instead of building an array. Good functions do one job named by a verb, take few typed parameters, avoid boolean flags, and are pure where possible: everything in through parameters, everything out through return, no echo, global, references or hidden state.
Why This Matters
The functions you write before launch will be called thousands of times a day by code you haven't written yet. The habits in this chapter — one job, typed, pure, loud when something is wrong — are what let the next developer (or you, in six months) use them without reading their insides.
never and generators are small features with big effects: one turns "the booking should have stopped" into a guarantee, the other lets the same foreach handle ten slots or ten million rows.
unknownService() now throws, and a misspelled service stops the booking. The 60-line function is three small ones. One job is left: the six files still each have their own price code. Mia has to replace all six with the same few functions, and prove that every screen shows the same price. That's the checkpoint.
