Advanced Type System — PHP

Types are written on the function (a named block of code). In function totalPrice(int $price, int $quantity): int, the int in front of each parameter (a…

The order quantity from a form (the input boxes on a web page) reaches the server as the text "2", not the number 2. PHP usually turns it into a number without telling you, and the total on the receipt is still right. Then one day "two" arrives, and the cash register program stops with an error halfway through. It's safer to write the rule "only numbers go in" plainly from the start.

In modern PHP, that rule is written right on a function (a named block of code you can run again and again): which type may go in, and which type comes out. Picture Mrs. Tini's cash drawer. It has a box for paper money, a box for coins and a box for receipts, each one labelled. If someone drops a receipt in the money box, Mrs. Tini refuses it right away, before the count goes wrong. In code, each box is one place where a value goes into a function. The labels on the boxes become type declarations: the type written for each place. Only a value of that type may go in. Mrs. Tini refusing the receipt is a TypeError, the error that appears when a value of the wrong type goes in.

Functions with types

The Functions lesson covers functions in full later. Here the basic shape is enough:

<?php

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

echo totalPrice(15, 2);
30

When the type doesn't fit

Form input is always a string, so $quantity often arrives as "2". The table shows the result of totalPrice(15, ...) for each second argument. The last column uses strict_types, a setting covered in the next section.

Second argument Without strict_types With strict_types
2 30 30
"2" 30, "2" turned into 2 TypeError, string given
"two" TypeError, string given TypeError, string given
2.5 30 plus a Deprecated TypeError, float given
null TypeError, null given TypeError, null given

Deprecated is a warning: this still works, but a later version of PHP may not support it. Here 2.5 is cut to 2.

With no setting at all, PHP uses coercive mode (a mode that changes the type when it can): a string that holds a number is turned into a number. "two" can't be turned into a number, so PHP stops:

Fatal error: Uncaught TypeError: totalPrice(): Argument #2 ($quantity) must be of type int, string given, called in /app/till.php on line 8 and defined in /app/till.php:3

Read the message from the left: the function totalPrice(), argument 2 ($quantity), should be int, a string came in, called on line 8, the function is written on line 3.

strict_types: no more guessing

This is the same code, with one new line below <?php, and "2" as the second argument:

<?php
declare(strict_types=1);

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

echo totalPrice(15, "2");
Fatal error: Uncaught TypeError: totalPrice(): Argument #2 ($quantity) must be of type int, string given, called in /app/till.php on line 9 and defined in /app/till.php:4

Nullable ? and union |

Mrs. Tini's cash register program looks up a price by menu code. The menu code can be a number (1) or text ("iced-tea"), and sometimes the menu code isn't found:

<?php
function menuPrice(int|string $code): ?int
{
    $prices = [
        1 => 15,
        "iced-tea" => 5,
    ];

    if (isset($prices[$code])) {
        return $prices[$code];
    }

    return null;
}

var_dump(menuPrice(1));
var_dump(menuPrice("iced-tea"));
var_dump(menuPrice(99));
int(15)
int(5)
NULL

== and ===

PHP has two ways to compare two values. The comment on each line is the result:

var_dump("15" == 15);  // bool(true)
var_dump("15" === 15); // bool(false)
var_dump(0 == "a");    // bool(false)
var_dump("1" == "01"); // bool(true)

Form input: check first, then convert. With strict_types, the input "2" has to become an int before it goes into totalPrice. (int) in front of a value forces it into an int. Don't just use (int), because it hides wrong input. filter_var($input, FILTER_VALIDATE_INT) is safer: it gives an int when the input is a whole number, and false when it isn't.

var_dump((int) "two");                             // int(0), no error
var_dump((int) "2abc");                            // int(2)
var_dump(filter_var("2", FILTER_VALIDATE_INT));    // int(2)
var_dump(filter_var("2abc", FILTER_VALIDATE_INT)); // bool(false)

$quantity = filter_var("two", FILTER_VALIDATE_INT);
if ($quantity === false) {
    echo "The quantity must be a whole number.";
} else {
    echo totalPrice(15, $quantity);
}

(int) "two" becomes 0 without any warning, so the receipt could print a total of 0. For "two", filter_var answers false. So the condition $quantity === false is true, the if writes a message, and the else part (which runs when the condition is false) is skipped. So totalPrice is never called. After the four var_dump lines, the code above writes The quantity must be a whole number. The Form Handling lesson uses filter_var again for form input.

📌 Other types you'll meet

⚠️ The first line, form input, and the forgotten null

TL;DR: Types are written on the function (a named block of code). In function totalPrice(int $price, int $quantity): int, the int in front of each parameter (a variable that receives a value) is the type allowed in, and : int is the type that comes out. With no setting, PHP turns "2" into 2, but refuses "two" and null with a TypeError (an error for a value of the wrong type). declare(strict_types=1); on the first line lets only an int in. ?int means an int or null (? = nullable), int|string means either one (| = union). A function with ?int still has to write return null, and null is checked with === null (exactly the same as null), not echo. == makes the types match first ("15" == 15 is true), === compares the value and the type, so make === your habit.

⚡ Types are written on the function

Write:

<?php

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

echo totalPrice(15, 2);

Meaning: A function is a named block of code you can call (run) again and again. The int in front of each parameter (a variable that receives a value) is the type allowed in, and : int after the brackets is the type of the value that comes out through return. The result is 30. If "two" goes in, PHP stops with a TypeError (an error for a value of the wrong type).

⚡ strict_types: no more guessing

Guess first: what does totalPrice(15, "2") give?

With no setting at all, 30: PHP turns "2" into 2. With declare(strict_types=1); on the first line, a TypeError.

Meaning: declare(strict_types=1); lets only an int into an int parameter. Write this line right after <?php, before any other statement.

⚡ ? allows null, | means either one

Write:

function menuPrice(int|string $code): ?int

Meaning: int|string means the parameter takes an int or a string (a union type). ?int means the result is an int or null (nullable). A function with ?int still has to write return null itself. Check for null with === null (exactly the same), not with echo, because echo null writes nothing.

What you will learn