截至PHP 7.0 ,标量类型提示 int、float、string 和 bool 可以包含在方法签名中。默认情况下,这些类型声明以弱/强制模式(或“type juggling”模式)运行。根据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.
但即使可以将 NULL 强制转换为整数 0,具有 int 类型提示的方法将拒绝强制转换 NULL<> 到整数 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
同样,即使it is possible将 NULL 强制转换为 bool 值 false,具有 bool 类型提示的方法将拒绝强制转换为 NULL 的入站值> 为 bool 值 false。 float 和 string 类型提示也是如此。
这种行为似乎与 php.net 上的文档相矛盾。这是怎么回事?
最佳答案
目前没有办法允许带有标量类型提示的方法自动输入声明类型的入站 NULL 值。
根据 RFC负责将此功能引入 PHP 7:
The weak type checking rules for the new scalar type declarations are mostly (emphasis added) the same as those of extension and built-in PHP functions. The only exception to this is the handling of NULL: in order to be consistent with our existing type declarations for classes, callables and arrays, NULL is not accepted by default, unless it is a parameter and is explicitly given a default value of NULL.
但是,在以下情况下,NULL 值可以被接受为 NULL:
<?php
class MyClass
{
// PHP 7.0+
public function testA(int $arg = null)
{
if (null === $arg) {
echo 'The argument is NULL!';
}
}
// PHP 7.1+
// https://wiki.php.net/rfc/nullable_types
public function testB(?int $arg)
{
if (null === $arg) {
echo 'The argument is NULL!';
}
}
}
$obj = new MyClass();
$obj->testA(null); // The argument is NULL!
$obj->testB(null); // The argument is NULL!
关于PHP7 : Methods with a scalar type declaration refuse to type juggle NULL values, 即使在弱/强制模式下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600400/