PHP by default lets you pass a string where an int is expected, and it’ll quietly convert it for you. Sounds convenient until you spend hours debugging a type-related bug that would’ve been caught immediately with strict types.
What declare(strict_types=1) Does
Drop this at the top of your PHP file and PHP will stop doing automatic type juggling. If a function expects an int and you pass a string, it throws a TypeError right away.
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
echo add(2, 3); // 5
echo add('2', 3); // TypeError: Argument 1 passed to add() must be of the type int, string given
Without strict types, that second call would silently convert '2' to 2 and you’d never know something was off. With strict types, it blows up immediately. That’s what you want.
Why Bother
- Bugs show up at dev time instead of production.
- Function signatures actually mean what they say.
- Easier to maintain — you know exactly what types flow through your code.
How to Use It
- Put
declare(strict_types=1);at the very top of the file, right after<?php. - Use it across your whole project, not just some files. Inconsistency defeats the purpose.
- Combine it with type hints on parameters and return types for maximum benefit.
References: