Functions and Type Declarations

Functions and Type Declarations in PHP: --- An automatic car wash is a fixed piece of apparatus that any driver can use without knowing how it works inside.


The Analogy: The Automatic Car Wash

An automatic car wash is a fixed piece of apparatus that any driver can use without knowing how it works inside. You steer onto the track, the machine takes over, and a defined sequence happens: pre-rinse, foam, brushes, rinse, blow dry. The whole point is that the sequence lives in one place and every car goes through the same proven steps. Nobody re-invents washing at each visit. A function is this apparatus in code: a named, reusable procedure you drive a value into, that runs its defined steps and hands something back. You call it by name and trust the sequence, exactly as a driver trusts the gantry.

Before the track even begins there are guide rails and a height barrier, and they are not decoration. The rails refuse a vehicle whose wheels are too wide, and the barrier stops a van that is too tall before it can reach the brushes. This is what a type declaration does for a parameter. Writing function wash(Car $vehicle) is the height barrier: the machine accepts a Car and turns away anything that is not one, and it does so at the entrance, before any work has started, rather than letting the wrong thing jam the brushes halfway through. The check happens up front, where the damage is cheapest to prevent.

Most car washes have a selector for the programme -- wash only, wash and wax, wash and wax and underbody -- and if you drive straight on without touching it, you get the standard programme. That untouched selector is a default argument: function wash(Car $vehicle, string $programme = 'standard') runs the standard cycle unless the caller asks for something else. And whatever programme you pick, the machine makes one promise about what comes out: a car, now clean. That guarantee is the return type. function wash(Car $vehicle): Car says the apparatus takes a car in and a car comes out; it cannot quietly hand you back a motorcycle, and PHP enforces that promise on the way out just as it enforced the parameter on the way in.

The failures divide neatly. If a vehicle simply does not fit -- a lorry at a car-only wash -- the barrier stops it at once with a clear refusal, and that is a TypeError: the wrong type of argument is rejected before the function body runs, at the exact point of the mistake. But there is a subtler failure the barrier cannot catch. Suppose the wax programme is selected, the car fits perfectly, the cycle runs -- and the wax tank was empty. The machine returns a car that looks washed and claims to be waxed but is not. Nothing was the wrong shape; the promise was simply not kept inside. Type declarations guard the shape of what goes in and comes out, never the correctness of what happens between, which is why a function can satisfy every type and still be wrong.


Syntax or Core Structure

A function declaration names the procedure, lists its parameters with optional type declarations and defaults, states a return type after the parameter list, and returns a value from its body. A parameter with a default may be omitted by the caller; parameters without defaults must be supplied. The return type constrains what the function may hand back.

<?php

function lineTotal(float $unit, int $qty, float $taxRate = 0.0): float
{
    $net = $unit * $qty;
    $gross = $net * (1 + $taxRate);
    return round($gross, 2);
}

echo lineTotal(4.50, 3), "\n";        // no tax: uses the default 0.0
echo lineTotal(4.50, 3, 0.20), "\n";  // 20% tax
echo lineTotal(19.99, 1, 0.05), "\n"; // 5% tax, rounded to 2 dp

The third parameter carries a default of 0.0, so the first call omits it and is taxed at zero. The return type float promises a floating-point result, and round keeps it to two decimal places. Each parameter's type declaration means PHP rejects an argument of the wrong type at the call, before the body runs.

Output:

13.5
16.2
20.99

Note that echo prints 13.5, not 13.50: a float carries no notion of trailing zeros, so display formatting (with number_format or printf) is a separate concern from the numeric value the function returns.


Technical Depth: Types, Coercion, and What the Signature Promises

The categories of type declaration

A type declaration can appear on each parameter and on the return. PHP groups the available types into a few families, and knowing them tells you what a signature is actually promising.

CategoryExamplesNote
Scalarint, float, string, boolThe four primitive value types
Compoundarray, object, callable, iterableStructures and things you can call or loop
Class or interfaceCar, PDO, CountableAn instance of that type
Nullable?int, ?stringThe type, or null
Special returnsvoid, never, static, selfvoid returns nothing; never cannot return

Beyond these, a union type such as int or string (written with a vertical bar between them) lets a parameter accept several types, and mixed accepts anything at all. A nullable type like ?float is shorthand for the union of that type with null, and is the correct way to declare a parameter that may legitimately be absent.

Coercive mode versus strict mode

By default PHP runs in coercive mode: when a scalar argument does not match its declared type but can be converted sensibly, PHP converts it. A function declaring int $n called with the numeric string "10" receives the integer 10. Placing declare(strict_types=1); at the very top of a file switches that file to strict mode, where the argument's type must match exactly (with one allowance: an int is accepted where a float is declared, since every integer is a valid float).

<?php
// coercive mode (no strict_types declaration)

function half(int $n): int
{
    return intdiv($n, 2);
}

echo half(10), "\n";     // a real integer
echo half("10"), "\n";   // the numeric string "10" is coerced to int 10

Both calls print the same result, because in coercive mode the string "10" is converted to the integer 10 before the body runs. Under declare(strict_types=1); the second call would instead throw a TypeError, because a string is not an int and strict mode does no conversion.

Output:

5
5

The practical guidance is to enable strict_types in your own files: coercion is convenient but it hides mistakes, silently turning "10 apples" into 10 with only a warning, whereas strict mode makes the caller pass the right type and surfaces the error at the boundary.


Real World Example: A Parcel Pricing Calculator

A dispatch desk prices each parcel from its weight, its destination zone, and whether express service was chosen. The rate per kilogram depends on the zone, a flat handling fee applies to every parcel, and express multiplies the total. A well-typed function captures this cleanly, with the express flag defaulting to off.

<?php
declare(strict_types=1);

function parcelCost(float $weight, string $zone, bool $express = false): float
{
    $rates = ['uk' => 2.00, 'eu' => 3.50, 'world' => 6.00];
    $handling = 1.50;

    $rate = $rates[$zone] ?? 2.00;
    $cost = $handling + $rate * $weight;
    if ($express) {
        $cost *= 1.5;
    }
    return round($cost, 2);
}

$parcels = [
    [2.0, 'uk',    false],
    [2.0, 'eu',    false],
    [1.5, 'world', true],
    [2.0, 'usa',   false],
];

echo "PARCEL PRICING\n";
echo str_repeat('-', 31), "\n";
printf("%-6s %-6s %-9s %7s\n", 'WEIGHT', 'ZONE', 'SERVICE', 'COST');
foreach ($parcels as [$weight, $zone, $express]) {
    printf(
        "%-6s %-6s %-9s %7s\n",
        number_format($weight, 1) . 'kg',
        $zone,
        $express ? 'express' : 'standard',
        number_format(parcelCost($weight, $zone, $express), 2)
    );
}

Output:

PARCEL PRICING
-------------------------------
WEIGHT ZONE   SERVICE      COST
2.0kg  uk     standard     5.50
2.0kg  eu     standard     8.50
1.5kg  world  express     15.75
2.0kg  usa    standard     5.50

The function reads well and the types carry real weight: strict_types means a caller cannot pass "2.0" as the weight and have it silently coerced, and the bool $express = false default lets the common case omit the flag entirely. The world parcel shows express working -- its base of 1.50 + 6.00 * 1.5 = 10.50 is multiplied by 1.5 to give 15.75. The array destructuring in the foreach unpacks each parcel row directly into named variables.

The output exposes a genuine design flaw, and it is one type declarations cannot catch. The usa parcel is priced at 5.50 -- exactly the same as the uk parcel -- because usa is not a key in the $rates array and the ?? 2.00 fallback silently applies the UK rate to an unknown destination. The types are all satisfied: usa is a perfectly valid string, so no TypeError fires, and the customer is quietly charged the wrong price with no error anywhere. This is the wax-tank-empty failure from the analogy: the shape was right, the promise was not kept. The fix is to validate the zone explicitly -- throw an InvalidArgumentException for an unknown zone, or model zones as an enum so only real zones can be passed -- rather than papering over a missing key with a default that happens to look plausible. A default rate is the most dangerous kind of bug, because it produces a believable number instead of a crash.


Common Mistakes

  1. Omitting type declarations entirely. A function whose parameters and return have no types accepts anything and promises nothing, pushing every type error to some later, more confusing point. Declare types on parameters and returns so mistakes surface at the call, where they are cheapest to fix.
  1. Relying on coercive mode to clean up input. Without strict_types, PHP quietly turns "10 apples" into 10 with only a warning, hiding a real bug. Enable declare(strict_types=1); at the top of every file so the caller must pass the correct type.
  1. Putting a required parameter after an optional one. Writing function f($a = 1, $b) forces the caller to pass $a just to reach $b, defeating the default. Parameters with defaults must come after all parameters without them.
  1. Using null as a default without a nullable type. Declaring string $name = null is deprecated in PHP 8.4; the honest form is ?string $name = null, which states plainly that null is an accepted value. Make the nullability explicit in the type.
  1. Expecting void functions to return a value. A function declared : void may only use a bare return; or none at all, and its result is null -- capturing $x = doThing() from a void function yields null, not a useful value. Declare a real return type when the caller needs the result.
  1. Confusing passing by value with passing by reference. By default PHP passes arguments by value, so modifying a parameter inside the function does not change the caller's variable. Only a parameter declared with & is passed by reference; do not assume a function mutates what you passed it.
  1. Depending on a default to mask missing data. A default like ?? 2.00 for an unknown lookup produces a plausible-looking wrong answer instead of an error, as the pricing example showed. Validate and reject unexpected input rather than defaulting past it.
  1. Declaring an over-broad return type. Returning mixed or leaving the return untyped forces every caller to guess and defend against every possibility. Return the narrowest type that is true -- a specific class, an array, an int -- so callers know what they are getting.
  1. Writing functions that do more than one thing. A function that fetches, transforms, and prints is hard to name, test, and reuse. Keep each function to a single responsibility so its signature honestly describes its whole job.

Best Practices

  • Put declare(strict_types=1); at the top of every PHP file so arguments must match their declared types exactly and coercion cannot hide a caller's mistake.
  • Declare a type on every parameter and on the return, choosing the narrowest type that is genuinely correct so the signature documents the function precisely.
  • Use ?type for a parameter that may legitimately be null, and give it a default of null, so absence is expressed in the type rather than implied.
  • Order parameters with required ones first and optional ones last, and prefer named arguments at the call site when a function has several optional parameters.
  • Return a value rather than printing inside the function; let the caller decide what to do with the result, which keeps the function testable and reusable.
  • Keep each function to a single responsibility, small enough that its name fully describes what it does.
  • Validate arguments whose validity the type system cannot express -- a zone that must be known, a number that must be positive -- and throw a clear exception when they are wrong, rather than defaulting past the problem.
  • Prefer pure functions that depend only on their arguments and avoid touching global state, since they are far easier to reason about and test.

Practice Exercises

  1. Write a function rectangleArea(float $width, float $height): float and call it with valid values, then add declare(strict_types=1); and call it with the string "5" for the width to observe the TypeError. Explain at which point the error is raised and why that is preferable to a silent conversion.
  1. Write a greet(string $name, string $greeting = 'Hello'): string function with a default greeting, and call it three ways: with both arguments positionally, with only the name, and using a named argument to set the greeting while omitting nothing else. Confirm the default applies only when the argument is omitted.
  1. Take the parcel pricing function and fix its design flaw: make it throw an InvalidArgumentException when the zone is not one of the known rates, then confirm that pricing a usa parcel now fails loudly instead of quietly charging the UK rate.
  1. Write a function applyDiscount(float $price, ?float $percent = null): float that returns the price unchanged when percent is null and applies the discount otherwise. Explain why ?float with a null default expresses "no discount given" more honestly than a default of 0.0 would.