🐘 PHP Intermediate

What is declare(strict_types=1) in PHP?

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.