将 int 传递给类型为 ?float 的参数会导致 PhpStorm 警告
Passing an int to a param of type ?float results in a PhpStorm warning
如果我打开 strict_types
,并且将 int
传递给一个设置为接受 ?float
作为参数类型的函数,PhpStorm 会发出警告,但代码仍然执行良好。有趣的是,如果参数类型只是 float
(没有 ?
),PhpStorm 不会发出警告。
例如:
<?
declare(strict_types=1);
function strictTypesTest (?float $float) {
echo $float;
}
strictTypesTest(42);
最后一行 (strictTypesTest(42);
) 有红色下划线和一条警告 Parameter is expected to be 'float|null', 'int' given
:
代码执行得很好,因为在 PHP docs on strict types 上,严格类型规则有一个例外:
The only exception to this rule is that an integer may be given to a function expecting a float.
如果我只将 float
作为参数类型(而不是 ?float
),那么 PhpStorm 不会发出警告。
为什么只有在我添加 ?
时才会触发警告
这似乎是一个错误,我已经在这里提交了:https://youtrack.jetbrains.com/issue/WI-38446
如果我打开 strict_types
,并且将 int
传递给一个设置为接受 ?float
作为参数类型的函数,PhpStorm 会发出警告,但代码仍然执行良好。有趣的是,如果参数类型只是 float
(没有 ?
),PhpStorm 不会发出警告。
例如:
<?
declare(strict_types=1);
function strictTypesTest (?float $float) {
echo $float;
}
strictTypesTest(42);
最后一行 (strictTypesTest(42);
) 有红色下划线和一条警告 Parameter is expected to be 'float|null', 'int' given
:
代码执行得很好,因为在 PHP docs on strict types 上,严格类型规则有一个例外:
The only exception to this rule is that an integer may be given to a function expecting a float.
如果我只将 float
作为参数类型(而不是 ?float
),那么 PhpStorm 不会发出警告。
为什么只有在我添加 ?
这似乎是一个错误,我已经在这里提交了:https://youtrack.jetbrains.com/issue/WI-38446