As of PHP 7.0, the scalar type hints int, float, string, and bool can be included in method signatures. By default, these type declarations operate in weak/coercive mode (or "type juggling" mode). According to the PHP manual:
PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
But even though it is possible to coerce NULL into the integer 0, a method with an int typehint will refuse to coerce an inbound value of NULL to the integer 0.
<?php
class MyClass
{
public function test(int $arg)
{
echo $arg;
}
}
$obj = new MyClass();
$obj->test('123'); // 123
$obj->test(false); // 0
$obj->test(null); // TypeError: Argument 1 passed to MyClass::test()
// must be of the type integer, null given
And similarly, even though it is possible to coerce NULL into the boolean false, a method with a bool typehint will refuse to coerce an inbound value of NULL to the boolean false. The same goes for the float and string type hints as well.
This behavior seems to contradict the documentation on php.net. What's going on here?