A PHP function is a named, reusable block of code that accepts input parameters, performs a task, and optionally returns a result. Breaking scripts into small single-purpose functions eliminates duplication and makes your code easier to test.
Modern PHP functions declare parameter types and an explicit return type (such as : float, : string, or : void). You can also assign default values to trailing parameters.
<?php
declare(strict_types=1);
function calculateDiscountedPrice(
float $price,
float $discountPercent = 10.0,
bool $roundResult = true
): float {
$discounted = $price * (1 - ($discountPercent / 100));
return $roundResult ? round($discounted, 2) : $discounted;
}
// Positional arguments
echo calculateDiscountedPrice(150.0, 20.0) . PHP_EOL;
// PHP 8 Named arguments allow skipping defaults cleanly
echo calculateDiscountedPrice(price: 99.99, roundResult: false) . PHP_EOL;
Named arguments let callers pass parameters by name rather than strict order, making boolean flags and optional settings self-documenting.
Use the spread operator ... to accept any number of arguments into an array, and use arrow functions (fn() => ...) for concise one-line callbacks.
<?php
declare(strict_types=1);
function sumInvoices(float ...$amounts): float
{
return array_sum($amounts);
}
$numbers = [2, 4, 6, 8];
$doubled = array_map(fn (int $n): int => $n * 2, $numbers);
echo "Invoice sum: " . sumInvoices(19.5, 40.0, 12.25) . PHP_EOL;
print_r($doubled);
: string or : void lets callers pass or receive unexpected null values silently.&$var).: void mean as a return type?: void tells PHP that the function performs an action (like printing or saving a file) and does not return any value.
An arrow function (fn($x) => $x * 2) automatically captures variables from the outer scope by value, whereas a regular closure (function ($x) use ($factor) { ... }) requires an explicit use clause.
Yes. PHP 8 supports union types like int|float or nullable types like ?string (string|null).
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.