strict_types in PHP – How It Works and Why It Matters

strict_types in PHP

By default, PHP uses what is known as “type juggling”, which means automatic type coercion. In practice, this means the PHP interpreter tries to “guess” what type you intend to use and converts values on the fly, without throwing errors or even warnings.

For example, if a function or operator expects a number but receives a string containing a digit (such as "5"), PHP will treat that string as a number and perform the conversion automatically. Similarly, when you combine a number with a string, PHP will attempt to adjust the types based on the context of the operation.

function add(int $a, int $b): int {
    return $a + $b;
}

echo add("5", 3); // Works, result: 8

This behavior can lead to bugs that are difficult to detect, because the program may sometimes behave differently than expected, especially when data comes from external sources such as forms, files, or APIs.

That’s why strict_types is often enabled in more complex projects. It prevents PHP from automatically converting types and forces values to match function declarations exactly. With strict_types enabled, function arguments must have the precise type that was declared:

declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

echo add("5", 3); // Fatal error: Argument #1 ($a) must be of type int, string given

Now PHP will throw an error, because "5" is a string, not an integer.