Functions with types and default values

Type the arguments and the return value. Optional arguments get a default.

PHP · Functions with types and default valuesBeginner
function price(float $amount, float $taxRate = 0.17, string $currency = 'PKR'): string
{
    $total = $amount * (1 + $taxRate);
    return number_format($total, 2) . ' ' . $currency;
}

echo price(1000);                          // 1,170.00 PKR
echo price(1000, currency: 'USD');         // named argument (PHP 8+)
echo price(1000, 0);                       // 1,000.00 PKR
functiontypesdefault