PHP Functions: Parameters, Return Types, and Scope

Last updated: August 27, 2026.

A PHP function packages one task behind a reusable name. Parameters supply inputs, and a declared return type makes the result easier to understand and verify.

Define and call a function

<?php
declare(strict_types=1);

function calculateTotal(float $price, int $quantity): float
{
    return $price * $quantity;
}

$total = calculateTotal(19.95, 3);
echo number_format($total, 2);
?>

Default and named arguments

<?php
declare(strict_types=1);

function formatPrice(float $amount, string $currency = 'USD'): string
{
    return $currency . ' ' . number_format($amount, 2);
}

echo formatPrice(amount: 24.5);
?>

Keep dependencies explicit

Variables declared inside a function are local to it. Pass required values as arguments instead of relying on mutable global state.

<?php
declare(strict_types=1);

function discountedPrice(float $price, float $rate): float
{
    return $price * (1 - $rate);
}

echo discountedPrice(100, 0.15);
?>

Use nullable and union types only when those alternatives are meaningful to callers. See user-defined functions in the PHP manual.

admin

admin

Leave a Reply

Your email address will not be published.