Functions are reusable blocks of code that execute when called. PHP 8 functions support scalar type hints, return type declarations, default parameter values, variadic arguments, and named parameters.
function functionName(type $param1, type $param2 = defaultValue): returnType
{
// Function Body
return $value;
}
flowchart TD
A["Function Invocation"] --> B["Validate Argument Types (strict_types=1)"]
B --> C["Execute Function Logic"]
C --> D["Validate Return Type"]
D --> E["Return Result Value to Caller"]
<?php
declare(strict_types=1);
/**
* Calculates item totals with tax and optional discount using named parameters.
*/
function calculateInvoiceTotal(
float $amount,
float $taxRate = 0.08,
float $discount = 0.0,
string ...$notes // Variadic parameter (captures extra trailing string arguments)
): float {
$taxableAmount = max(0.0, $amount - $discount);
$total = $taxableAmount + ($taxableAmount * $taxRate);
if (!empty($notes)) {
// Process notes
}
return round($total, 2);
}
// Invoking function with PHP 8 Named Arguments (Order doesn't matter!)
$finalTotal = calculateInvoiceTotal(
amount: 250.00,
discount: 50.00, // Skipped $taxRate to use default 0.08!
notes: "Applied Spring Coupon", "Expedited Shipping"
);
echo "Final Invoice Total: $" . $finalTotal . "
";
// Arrow Function (Anonymous Closure)
$multiplier = 3;
$numbers = [1, 2, 3, 4];
$tripled = array_map(fn(int $n): int => $n * $multiplier, $numbers);
echo "Tripled Numbers: " . implode(", ", $tripled) . "
";
: int, : string, : void).amount: 100, discount: 10) to eliminate ambiguous boolean flags.fn() for Short Closures: Simplifies single-expression closures passed to array_map(), array_filter(), and usort().Write a typed function formatCurrency(float $amount, string $currency = 'USD'): string that returns $amount formatted to 2 decimal places prefixed by the currency code!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.