Advertisement
Beginner PHP, Type Declarations & Strict Types

What does declaring strict_types=1 at the top of a PHP file actually change about how type declarations are enforced?

Short answer

By default, PHP operates in what is called coercive typing mode, meaning it will automatically attempt to convert a value to the expected declared type if possible, such as silently converting the string ten into the integer ten, whereas adding the declare strict_types equals…

Save PHP mock interview
Advertisement
AModel answer
By default, PHP operates in what is called coercive typing mode, meaning it will automatically attempt to convert a value to the expected declared type if possible, such as silently converting the string ten into the integer ten, whereas adding the declare strict_types equals one statement at the very top of a file switches that specific file into strict mode, meaning PHP will now raise a type error immediately if a value's type does not exactly match the declared type, rather than silently attempting to convert it, which helps catch subtle bugs caused by unintended, unexpected type conversions.
declare(strict_types=1);

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

addNumbers('5', 3); // Throws a TypeError in strict mode
Real-world example
A financial calculation module enables strict_types at the top of every file, ensuring that an accidental string value can never silently sneak into a monetary calculation without immediately raising a clear, visible error.
Likely follow-ups
  • Does enabling strict_types in one file affect type checking behavior in other files that call into it?
  • What are the tradeoffs of using strict types throughout an entire codebase?
Related topics