I'm using PHP 7.4.16. I enabled strict_types
in my PHP file thinking it would prevent passing a string
argument to a function expecting an int
by throwing a TypeError
. However, the function actually accepts the string
and coerces it to an int
. But if I place a return type hint on the function it works as expected, throwing a TypeError
.
This doesn't make sense to me and seems like a glaring inconsistency that can lead to bugs. Does anyone have any insight as to why this is or if I'm doing something wrong?
Test code:
<?phpdeclare(strict_types=1);$ids = ['1', '2', '3'];// No error thrown, coerces string argument to int.array_map(fn (int $id) => $id, $ids);// Throws PHP Fatal error: Uncaught TypeError: Return value of {closure}() must be of the type int, string returnedarray_map(fn ($id): int => $id, $ids);