🐘 PHP Intermediate

What is declare(strict_types=1) in PHP?

Why Interviewers Ask This

Mid-level PHP roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Adding declare(strict_types=1); at the very top of a PHP file (before any other code) enables strict type mode for that file. In strict mode, PHP enforces type declarations strictly — passing a string where an int is declared throws a TypeError instead of coercing the type. Example: with strict types, calling add("5", 3) on a function declared as function add(int $a, int $b) throws an error. Without strict types, PHP would quietly convert "5" to 5. Strict types apply per-file — other files calling your functions still use coercive mode unless they also declare strict types. This is highly recommended for all new code to catch type errors at development time rather than having silent coercions cause bugs in production.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.