Advertisement
Advanced PHP, Basics & Types

How does PHP's type coercion behave differently in strict types mode compared to the default coercive mode, and what are the implications for function argument and return type validation?

Short answer

In PHP's default coercive typing mode, scalar type declarations on function parameters and return values are automatically converted where possible, such as a string containing digits being silently converted to an integer, while declaring strict_types at the very top of a file…

Save PHP mock interview
Advertisement
AModel answer
In PHP's default coercive typing mode, scalar type declarations on function parameters and return values are automatically converted where possible, such as a string containing digits being silently converted to an integer, while declaring strict_types at the very top of a file disables this automatic coercion for that specific file, meaning a mismatched type passed into a strictly typed function throws a TypeError immediately rather than being silently converted, catching potential bugs much earlier in the development process.
declare(strict_types=1);

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

addNumbers("5", 3); // Throws TypeError under strict_types
Real-world example
A team adopts strict_types across their entire codebase after discovering that a silently coerced string value had caused an incorrect calculation deep within their billing system, catching similar issues immediately as TypeErrors going forward instead of producing subtly wrong results.
Likely follow-ups
  • Does declare(strict_types=1) affect the entire application or just the specific file it appears in?
  • How does strict typing interact with nullable type declarations?
Related topics