What does declare(strict_types=1); do in PHP 7+ and why should you use it?
❓ Interview Prompt: Explain type coercion in default PHP vs strict type enforcement, type hints, and scalar return types.
Historically, PHP was a weakly-typed language that performed aggressive automatic type coercion. For example, if a function expected an integer 'function add(int $a, int $b)', calling 'add("10", "20")' would silently coerce the strings into integers and return '30'.
What 'declare(strict_types=1);' Does:
When you place 'declare(strict_types=1);' as the very first statement at the top of a PHP file, PHP disables automatic type coercion for all function calls made inside that file.
Best Practice (2026):
Always enable 'declare(strict_types=1);' at the top of every class and script in modern PHP engineering to catch type mismatch bugs immediately during development.
Code Implementation Example
<?php
declare(strict_types=1); // MUST be the very first line of code!
function calculateTotal(int $price, int $quantity): int {
return $price * $quantity;
}
// Correct: Passing strict integers
echo calculateTotal(100, 5); // Outputs: 500
// Fatal Error in strict_types=1! (Would silently coerce in default PHP!)
// TypeError: calculateTotal(): Argument #1 ($price) must be of type int, string given
// echo calculateTotal("100", 5);Always put declare(strict_types=1); at the top of PHP files to disable silent type coercion and enforce strict scalar type hints.