Default Values and Named Arguments
A default value makes a parameter optional, and a named argument passes a value to a parameter by name, which lets a call skip optional parameters and makes it self-explanatory.
Compare omitted arguments, positional calls and explicit argument names.
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.