In this chapter
We'll learn how parameter and return types turn a function into a promise: what happens when a wrong type arrives with and without strict_types, why int $x = null is deprecated and ?int is the fix, union types like int|float, and the special return types void and never — with the mobile app that sent pounds where the function expected pence.
The Problem in Real Life
The mobile app calls api.php with the price of the chosen service. Mia swaps the old copy there for calculatePrice(), and the app shows Daniel's haircut with a hot towel for £0.27.
Marcus opens the app's request: "price": 27.5. The app sends pounds, as a decimal number. calculatePrice() expects pence, as an int. And api.php, unlike the other files, has no declare(strict_types=1); at the top — so PHP turned 27.5 into 27 and printed a "Deprecated" line into a log nobody reads.
The parameter says int. Why did PHP accept 27.5 at all?
Mia
A Suggestion vs. a Promise
Types are a contract
int $pence promises the function a whole number. The question is what PHP does when a caller breaks the promise.
Quiet conversion
Without strict_types, PHP converts 27.5 into 27 to fit an int parameter — with a deprecation notice, not an error.
Maybe a value, maybe not
A discount code may be missing. Saying so in the type — ?string — is clearer than a silent default.
Parameter and Return Types
Types on functions: you met PHP's types in Act 04 and declare(strict_types=1) in Act 02. This chapter is about using them where they matter most — on a function's parameters and its return value:
- Parameter types: what each parameter accepts.
- Return types: what the function promises to give back.
- Strict and coercive mode: what PHP does with a wrong type.
- Nullable and union types:
?intandint|float, plusvoidandnever.
Parameter types: function calculatePrice(int $basePence, int $addOnPence) declares that both parameters must be integers. Inside the function you can rely on it: no need to check whether $basePence might be a string or an array. The types you'll use most are int, float, string, bool and array, plus class names from Act 11. A parameter without a type accepts anything, which also means the function has to defend itself against anything.
Return types: : int after the brackets promises what comes back. PHP checks it on every return: a function declared : string that tries to return an array throws a TypeError, right there, instead of handing a surprise to the caller. A return type is also documentation: formatPrice(int $pence): string tells you everything you need without reading the body.
<?phpfunction formatPrice(int $pence): string{if ($pence < 0) {return ["error" => "negative"]; // breaks the promise}return "£" . number_format($pence / 100, 2);}echo formatPrice(2750), "\n"; // £27.50try {formatPrice(-1);} catch (TypeError $e) {echo $e->getMessage(), "\n";}// formatPrice(): Return value must be of type string, array returned
Coercive mode, the default: without declare(strict_types=1) at the top of the calling file, PHP tries to convert a wrong scalar value to the declared type: "2750" becomes 2750, true becomes 1, and the float 27.5 becomes the int 27. Since PHP 8.1, losing a fraction like that triggers a deprecation notice, but the call still runs. That's how api.php turned £27.50 into 27 pence. Values that can't be converted at all, like "abc" for an int, throw a TypeError even in this mode.
<?php// api.php — no declare(strict_types=1) herefunction calculatePrice(int $basePence, int $addOnPence): int{return $basePence + $addOnPence;}$fromApp = 27.5; // the app sends poundsvar_dump(calculatePrice($fromApp, 0));var_dump(calculatePrice("2500", true)); // also converted: "2500" → 2500, true → 1// Deprecated: Implicit conversion from float 27.5 to int loses precision// int(27)// int(2501)
Strict mode: with declare(strict_types=1); as the first statement of a file, every call made from that file must pass exactly the declared type. 27.5 for an int is a TypeError with a clear message, and the bug is found on the first test instead of in a customer's app. There's one convenient exception: an int is accepted where a float is declared. Strict mode belongs to the file that makes the call, so it has to be at the top of every file — api.php was the one without it. The fix there has two parts: add strict_types, and convert the app's pounds to pence at the edge, where the data arrives: (int) round($pounds * 100).
<?phpdeclare(strict_types=1);function calculatePrice(int $basePence, int $addOnPence): int{return $basePence + $addOnPence;}$fromApp = 27.5;try {calculatePrice($fromApp, 0);} catch (TypeError $e) {echo $e->getMessage(), "\n";}// calculatePrice(): Argument #1 ($basePence) must be of type int, float given, called in main.php on line 12$pence = (int) round($fromApp * 100); // convert where the data arrivesecho calculatePrice($pence, 0), "\n"; // 2750
Nullable types: sometimes "no value" is a valid answer: a booking may or may not have a discount code. ?string $discountCode means "a string or null". Give it a default, ?string $discountCode = null, and callers can leave it out. In old code you'll see string $code = null without the ?; that made the type nullable silently, and since PHP 8.4 it's deprecated: write the ? yourself. A return type can be nullable too: findBooking(int $id): ?array returns a booking or null.
<?phpdeclare(strict_types=1);function applyDiscount(int $pence, ?string $code = null): int{if ($code === null) {return $pence;}return $code === "OPENING10" ? $pence - intdiv($pence * 10, 100) : $pence;}echo applyDiscount(2500), " ", applyDiscount(2500, "OPENING10"), "\n"; // 2500 2250function oldStyle(int $pence, string $code = null): int // the old way{return $pence;}// Deprecated: oldStyle(): Implicitly marking parameter $code as nullable is deprecated, the explicit nullable type must be used instead// (PHP shows this while reading the file, so it appears above the other output)
Union types and the special return types: int|float $amount accepts either type; string|false is common in PHP's own functions, which often return false on failure. Use unions sparingly — a function that accepts three types has to handle three cases. Two return types say "nothing comes back": void means the function returns nothing useful (a bare return; is allowed), and never means it never returns at all, because it always throws or exits (chapter 10). The table below sums up the forms.
| Declaration | Accepts or returns | Example |
|---|---|---|
| int $pence | An int (and, without strict_types, values that convert) | calculatePrice(int $basePence, ...) |
| : string | Must return a string | formatPrice(int $pence): string |
| ?string $code = null | A string or null; may be left out | applyDiscount(int $pence, ?string $code = null) |
| : ?array | An array or null | findBooking(int $id): ?array |
| int|float $amount | Either type | toPence(int|float $pounds): int |
| : void | Returns nothing (bare return; allowed) | logPrice(int $pence): void |
| : never | Never returns: always throws or exits | fail(string $message): never |
<?phpdeclare(strict_types=1);function toPence(int|float $pounds): int{return (int) round($pounds * 100);}function logPrice(int $pence): void{if ($pence === 0) {return; // nothing to log: leave early}echo "[price] $pence\n";}echo toPence(25), " ", toPence(27.5), "\n"; // 2500 2750logPrice(0);logPrice(2750); // [price] 2750
Key Takeaway
Parameter and return types turn a function into a promise that PHP checks. Without strict_types, PHP converts scalars to fit (27.5 becomes 27, with only a deprecation notice); with declare(strict_types=1) in the calling file, a wrong type is a TypeError. Use ?type for "this or null" (int $x = null is deprecated since PHP 8.4), unions like int|float sparingly, void for "returns nothing" and never for "never returns".
Why This Matters
A price function that silently turns pounds into pence — or 27.5 into 27 — is how money goes missing without anyone noticing. Types on the boundary of a function, checked strictly, turn that silent wrong answer into a loud error on the first test run.
Types are also the cheapest documentation there is. findBooking(int $id): ?array tells the next developer (and your editor) what goes in, what comes out, and that "nothing found" is possible — without a single comment.
api.php now has strict_types and converts the app's pounds to pence on arrival. Mia moves on to admin.php, where Tom can book a customer by hand. The admin copy calls calculatePrice("haircut", [], true, false) — and Tom's own staff discount is being charged as a holiday surcharge. Which true was which? That's the next chapter: default, named and variadic arguments.
