In this chapter
We'll learn how to make parameters optional with default values, how named arguments make calls readable and let you skip optional parameters, how variadic parameters (...$addOns) accept any number of values, and how to unpack an array into arguments — with the call where two trues swapped a staff discount and a holiday surcharge.
The Problem in Real Life
admin.php is where Tom books a customer by hand. Its copy of the price calculation was turned into a function months ago: adminPrice(string $service, array $addOns, bool $isHoliday, bool $isStaff). Tom booked his own nephew today, a staff booking, with adminPrice("haircut", [], true, false).
The nephew was charged a holiday surcharge instead of getting the staff discount. Reading the line, Mia can't tell either: which true is which?
true, false — I have to open the function to know what those mean. Can the call say it?
Mia
Arguments by Position vs. Arguments by Name
true, false, what?
A call with several booleans in a row hides what each one means. Swap two, and the code still runs.
Most callers want the defaults
Most bookings have no add-ons and aren't on a holiday. Callers shouldn't have to say so every time.
Any number of add-ons
One booking has no add-ons, another has three. The function should accept however many there are.
Default, Named and Variadic Arguments
Flexible, readable calls: a function is written once but called many times, so its calls should be easy to write and easy to read. Four features help:
- Default values: parameters callers may leave out.
- Named arguments: saying which parameter a value is for, by name.
- Variadic parameters: one parameter that collects any number of values.
- Argument unpacking: spreading an array into separate arguments.
Default values: bool $isHoliday = false gives a parameter a default: callers can leave it out, and it's false. Defaults must be constant values — a number, a string, null, an array, a constant like HOLIDAY_RATE — not a function call or a variable. Parameters with defaults go after the required ones. If you put an optional parameter before a required one, PHP treats it as required anyway and, since PHP 8.0, warns you with a deprecation notice.
<?phpdeclare(strict_types=1);const PRICES = ["haircut" => 2500, "beard-trim" => 1000, "hot-towel" => 250];function servicePrice(string $service, bool $isHoliday = false): int{$pence = PRICES[$service];return $isHoliday ? $pence + intdiv($pence * 10, 100) : $pence;}echo servicePrice("haircut"), "\n"; // 2500: $isHoliday is falseecho servicePrice("haircut", true), "\n"; // 2750function wrongOrder($isHoliday = false, $service) // optional before required{}// Deprecated: wrongOrder(): Optional parameter $isHoliday declared before required parameter $service is implicitly treated as a required parameter// (PHP shows this while reading the file, so it appears above the other output)
Named arguments: since PHP 8.0 you can pass an argument by the parameter's name: adminPrice("haircut", isStaff: true). The name, a colon, then the value. Now the call says what it means, the order of named arguments doesn't matter, and you can skip optional parameters in the middle — isHoliday keeps its default. That's Mia's fix: no more rows of true, false. Two rules: positional arguments must come first (f(base: 1, 2) is a compile error), and a misspelled name is an Error, "Unknown named parameter", which is much better than silently swapping two booleans. Because callers can now use them, parameter names become part of how the function is used — rename them with care.
<?phpdeclare(strict_types=1);function adminPrice(string $service, array $addOns = [], bool $isHoliday = false, bool $isStaff = false): string{return $service . ($isHoliday ? " +holiday" : "") . ($isStaff ? " -staff" : "");}echo adminPrice("haircut", [], true, false), "\n"; // haircut +holiday — meant staff!echo adminPrice("haircut", isStaff: true), "\n"; // haircut -staff: says what it meansecho adminPrice(isStaff: true, service: "haircut"), "\n"; // any order// haircut +holiday// haircut -staff// haircut -staff
<?phpdeclare(strict_types=1);function adminPrice(string $service, bool $isHoliday = false, bool $isStaff = false): string{return $service;}try {adminPrice("haircut", isStaf: true);} catch (Error $e) {echo $e->getMessage(), "\n";}// Unknown named parameter $isStaf
Variadic parameters: a parameter written with three dots, string ...$addOns, collects all the remaining arguments into an array. So calculatePrice("haircut"), calculatePrice("haircut", "hot-towel") and calculatePrice("haircut", "hot-towel", "beard-trim") all work, and inside the function $addOns is [], ["hot-towel"] or ["hot-towel", "beard-trim"]. The variadic parameter must be the last one, and its type, if given, applies to every value. PHP's own max(), sprintf() and array_push() work this way.
<?phpdeclare(strict_types=1);const PRICES = ["haircut" => 2500, "beard-trim" => 1000, "hot-towel" => 250];function calculatePrice(string $service, string ...$addOns): int{$total = PRICES[$service];foreach ($addOns as $addOn) {$total += PRICES[$addOn];}return $total;}echo calculatePrice("haircut"), "\n"; // 2500echo calculatePrice("haircut", "hot-towel"), "\n"; // 2750echo calculatePrice("haircut", "hot-towel", "beard-trim"), "\n"; // 3750
Argument unpacking: the same three dots in a call do the opposite: calculatePrice("haircut", ...$chosen) spreads the array $chosen into separate arguments. It's the spread operator from Act 08 again. If the array has string keys, they become named arguments: adminPrice(...["service" => "haircut", "isStaff" => true]).
<?phpdeclare(strict_types=1);const PRICES = ["haircut" => 2500, "beard-trim" => 1000, "hot-towel" => 250];function calculatePrice(string $service, string ...$addOns): int{return PRICES[$service] + array_sum(array_map(fn($a) => PRICES[$a], $addOns));}$chosen = ["hot-towel", "beard-trim"]; // from the booking formecho calculatePrice("haircut", ...$chosen), "\n"; // 3750$booking = ["service" => "beard-trim"];echo calculatePrice(...$booking), "\n"; // 1000: string keys become named arguments
Too many flags is a design smell: even with named arguments, a function with four booleans has sixteen combinations to get right. When parameters pile up, consider splitting the function (staffPrice(), holidayPrice()), or passing one array or object that describes the booking (Act 11). Chapter 10 comes back to this. The table below sums up the syntax.
| Feature | Declaration | Call |
|---|---|---|
| Positional | f(string $service, bool $isHoliday) | f("haircut", true) |
| Default value | f(string $service, bool $isHoliday = false) | f("haircut") |
| Named argument (PHP 8.0) | f(string $service, bool $isHoliday = false, bool $isStaff = false) | f("haircut", isStaff: true) |
| Variadic parameter | f(string $service, string ...$addOns) | f("haircut", "hot-towel", "beard-trim") |
| Unpacking a list | f(string $service, string ...$addOns) | f("haircut", ...$chosen) |
| Unpacking named | f(string $service, bool $isStaff = false) | f(...["service" => "haircut", "isStaff" => true]) |
Key Takeaway
Defaults (= false) make parameters optional; put them after the required ones. Named arguments (isStaff: true) make calls readable, ignore order, skip optional parameters and catch typos — positional ones come first. A variadic parameter (string ...$addOns) collects any number of arguments into an array and must be last; ... in a call unpacks an array into arguments.
Why This Matters
A call like adminPrice("haircut", [], true, false) is a bug waiting for the next reader: nothing in it says which flag is which, and swapping two booleans still runs. Named arguments make the meaning part of the call, and turn a typo into an error instead of a wrong price.
Defaults and variadics keep the common case short — calculatePrice("haircut") — while the unusual case stays possible. Laravel uses named arguments, defaults and variadics everywhere, so you'll read these forms constantly in the next course.
admin.php calls adminPrice("haircut", isStaff: true), and Tom's nephew gets his discount. Next, Mia looks at the checkout preview: it shows the price with the surcharge, and when the customer presses "Pay", checkout calculates again. Daniel's card was charged £33.27 — the surcharge was added twice. The helper both screens use takes the booking with an &. That's the next chapter: pass by value vs. pass by reference.
