class Tests
{
function test(string $name)
{
var_dump($name);
}
}
$test = new Tests();
$test->test('tpunt');
$test->test(null); //由此会行引发的错误
$test->test(); //由此会行引发的错误
PHP7.0 中会报错.如下:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type string, null given, called in .....
TypeError: Argument 1 passed to test() must be of the type string, null given, called in ....
在PHP7.1当中只需要在类型前面加 ? 即可解决null 报错,什么值都不传的情况仍然会报错.
?string $name
结果
test(); //此行仍然会引发的错误
--------------------------
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type string, null given, called in .....
TypeError: Argument 1 passed to test() must be of the type string, null given, called in ....