Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

PHP Functions: Types, Defaults, Named Arguments and Closures

6 min read Updated By the SkillNewton team

What is a function in PHP?

A function in PHP is a named, reusable block of code that takes zero or more inputs (parameters), does one job and can send back a result with return. You declare it with the function keyword and call it by name. Type declarations, default values, named arguments and closures let you write functions that are clear, safe and easy to reuse.

Key terms: parameters, arguments, return values and scope

  • Parameter: a variable listed in the function declaration, such as $price.
  • Argument: the actual value you pass when calling the function, such as 499.
  • Return value: the result sent back by return. A function without one returns null.
  • Scope: variables created inside a function exist only inside it. A function cannot see outside variables unless you pass them in.

PHP ships with thousands of built-in functions, such as strlen(), number_format() and array_sum(), documented in the official PHP manual. Check the manual before writing your own: a built-in function is usually faster and already handles edge cases. User-defined functions are the ones you write, and you can call them before or after their declaration in the same file, as long as they are not declared inside a condition.

Functions keep your code short and testable: write a rule such as "add 18 per cent GST" once and call it everywhere. If you are still learning variables and loops, start with the introduction to PHP.

Typed parameters, return types, defaults and named arguments

Type declarations state what a function accepts and returns. Default values make a parameter optional, and named arguments (PHP 8.0 and later) let you pass values by name, so you can skip optional parameters and keep calls readable.

<?php
declare(strict_types=1);

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

echo formatPrice(1499.5);                 // INR 1,499.50
echo formatPrice(1499.5, decimals: 0);    // INR 1,500
echo formatPrice(amount: 20, currency: 'USD'); // USD 20.00
TypeMeaning
?stringA string or null (nullable type)
int|floatEither type (union type, PHP 8.0)
voidReturns nothing
neverNever returns: always throws or exits (PHP 8.1)
mixedAny value; use sparingly

Parameters with defaults must come after required ones. Named arguments use the parameter name, so renaming a parameter in a shared library is a breaking change for anyone calling it by name.

How strict_types changes type checking

By default PHP runs in coercive mode: if a function expects an int and receives the string "5", PHP quietly converts it. Adding declare(strict_types=1); as the first statement of a file switches calls made from that file to strict mode, where a wrong type throws a TypeError.

<?php
declare(strict_types=1);

function addGst(float $price): float
{
    return round($price * 1.18, 2);
}

echo addGst(100);    // 118: an int may widen to float
echo addGst('100');  // TypeError: string given

Variadic parameters and passing by reference

A variadic parameter, written ...$name, collects any number of arguments into an array. The same ... operator at a call site spreads an array into separate arguments. Normally PHP passes a copy of each value; an & before the parameter passes a reference, so the function changes the caller's variable.

<?php
declare(strict_types=1);

function total(int ...$amounts): int
{
    return array_sum($amounts);
}

echo total(100, 250, 75);   // 425
$cart = [100, 250];
echo total(...$cart);       // 350

function addItem(array &$items, string $item): void
{
    $items[] = $item;
}

$basket = [];
addItem($basket, 'Notebook');
echo count($basket);        // 1

Use references rarely. A function that returns a new value is easier to follow than one that silently changes its input. Many built-in functions, such as sort(), take arrays by reference, which is why they change the array you pass rather than returning a sorted copy.

Handling bad input: nullable returns, exceptions and early returns

A function needs a clear answer for input it cannot handle. Return null through a nullable type when "nothing found" is a normal outcome, such as looking up a product that may not exist. Throw an exception when the caller has made a mistake, such as passing a negative quantity. Guard clauses at the top of the function return or throw early, which keeps the main logic unindented and easy to read.

<?php
declare(strict_types=1);

function findDiscount(string $code): ?float
{
    $codes = ['DIWALI10' => 0.10, 'STUDENT' => 0.15];
    return $codes[strtoupper($code)] ?? null;
}

function shippingCharge(int $weightGrams): int
{
    if ($weightGrams <= 0) {
        throw new InvalidArgumentException('Weight must be positive.');
    }
    if ($weightGrams <= 500) {
        return 40;
    }
    return 40 + (int) ceil(($weightGrams - 500) / 500) * 20;
}

$discount = findDiscount('student') ?? 0.0;   // 0.15
echo shippingCharge(1200);                    // 80

try {
    shippingCharge(0);
} catch (InvalidArgumentException $e) {
    echo $e->getMessage();                    // Weight must be positive.
}

Avoid returning false for errors and a number for success: callers forget to check, and 0 and false are easy to confuse in loose comparisons.

Closures, arrow functions and static variables

An anonymous function (closure) has no name and can be stored in a variable or passed to another function. It reaches outside variables only through use. An arrow function, fn, is a one-expression shorthand that captures outside variables automatically, by value. A static variable inside a function keeps its value between calls.

<?php
declare(strict_types=1);

$rate = 0.18;
$withTax = function (float $price) use ($rate): float {
    return round($price * (1 + $rate), 2);
};
$withTaxShort = fn (float $price): float => round($price * (1 + $rate), 2);

print_r(array_map($withTaxShort, [100, 250.5])); // [118, 295.59]

$count = 0;
$increment = function () use (&$count): void { $count++; };
$increment();
$increment();
echo $count;               // 2

function nextInvoiceNumber(): int
{
    static $number = 1000;
    return ++$number;
}
echo nextInvoiceNumber();  // 1001
echo nextInvoiceNumber();  // 1002

$upper = strtoupper(...);  // first-class callable (PHP 8.1)
echo $upper('php');        // PHP

Closures shine with array functions such as array_map() and usort(), covered in the PHP arrays guide. Methods inside classes follow the same rules, as the object-oriented PHP guide shows.

Writing good functions step by step

  1. Name the function with a verb that describes its single job, such as calculateShipping().
  2. Type every parameter and the return value.
  3. Keep required parameters first and give sensible defaults to the rest.
  4. Return a value rather than echoing it, so callers decide how to display it.
  5. Throw an exception for invalid input instead of returning a mix of values and false.
  6. Keep it short: if it needs a scroll bar, split it into smaller functions.

Group related functions in one file, such as helpers/money.php, and include it once with require_once. Declaring the same function twice is a fatal error. As a project grows, move them into classes loaded by Composer, and keep each function small enough that you can test it on its own with a few sample inputs and expected outputs.

Practical exercise: build a small invoice helper library

Create invoice.php with declare(strict_types=1); and write these functions:

  • lineTotal(int $qty, float $unitPrice, float $discount = 0.0): float, rounding to two decimals.
  • invoiceTotal(float ...$lines): float using a variadic parameter.
  • applyTax(float $amount, float $rate = 0.18): float, called once with a named argument.
  • An arrow function passed to array_map() that formats every line as INR 1,234.00.
  • A nextInvoiceNumber() function using a static variable.

You are done when php invoice.php prints three formatted lines, a total with tax and two consecutive invoice numbers, and passing a string quantity throws a TypeError. The PHP foundation course practises these patterns in its projects.

Common mistakes

  • Expecting a function to see a global variable without passing it in as a parameter.
  • Echoing output inside a function instead of returning a value the caller can reuse.
  • Placing an optional parameter before a required one, which PHP deprecates.
  • Forgetting use in a closure, then getting an "undefined variable" warning.
  • Using references to return several values when returning an array or object would be clearer.
  • Leaving out declare(strict_types=1), so wrong types are silently converted.

Frequently asked questions

What is the difference between a closure and an arrow function?

A closure can contain many statements and needs use to read outside variables. An arrow function holds one expression and captures outside variables automatically, by value, so it cannot change them.

Can a PHP function return more than one value?

Return an array and destructure it, as in [$min, $max] = minMax($numbers);, or return a small object when the values belong together.

Does strict_types affect the whole application?

No. It applies only to function calls written in the file that declares it. Each file must declare it separately.

Are function names case-sensitive in PHP?

Function names are not case-sensitive, but variable names are. Call functions with the same spelling you declared them with to keep code consistent.

Want to Learn This Properly?

The PHP Web Development: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.