Default Values and Named Arguments
Pageturn's price function takes a base price, a VAT rate and a discount. Almost every call uses the standard VAT and no discount, yet each call still spells out all three. Worse, price(10, 0.1) gives no hint whether 0.1 is the VAT or the discount. Defaults and named arguments fix both problems.
The rule
Defaults make arguments optional; names make them clear and skippable.
<?php
function price(float $base, float $vat = 0.20, float $discount = 0.0): float
{
return round($base * (1 + $vat) * (1 - $discount), 2);
}
echo price(10); // 12: both defaults used
echo price(10, 0.05); // 10.5: reduced VAT, no discount
echo price(10, discount: 0.5); // 6: VAT default, half price
echo price(base: 10, discount: 0.1); // 10.8Default values. float $vat = 0.20 means "if the caller leaves this out, use 0.20". Rules:
- Defaults must be fixed values: numbers, strings,
null, arrays, constants. Not a function call such astime(). - Put optional parameters after required ones. A required parameter after an optional one makes the default useless, and PHP 8 warns about it.
- A common pattern is
?string $coupon = null, meaning "maybe absent".
Named arguments (PHP 8.0) let a call say which parameter each value is for: discount: 0.5. That gives you two powers:
- Skipping. Without names you cannot give a discount without also repeating the VAT. With names you jump straight to it.
- Clarity.
price(10, discount: 0.1)documents itself.
Rules for names:
- Positional arguments come first, then named ones.
price(discount: 0.5, 10)is a compile error. - The name must match a real parameter.
price(10, rate: 0.1)throws an error for the unknown parameter$rate. - Named arguments also work with built-in functions, for example
htmlspecialchars($text, double_encode: false).
A side effect: once people call your function with names, renaming a parameter breaks their code. Parameter names are now part of the public contract.
The shortcut
At every call, ask "would a reader know what each value means?" Bare true, 0.1 or null in the middle of a call usually deserves a name.
The call
price(10, 0.20, 0.25)— the 0.20 is just the default, repeated.
Drills
Answer fast — trust the rule.
What does price(20) return?
Which call applies a 10% discount while keeping the default VAT?
Why is price(discount: 0.5, 10) rejected?
Which parameter list is correctly ordered?
Remember
- Defaults make arguments optional; names make them clear and skippable.
- Shortcut: a bare mystery value in a call deserves a name.
- Trap: positional before named, and renaming a parameter can break callers.
