在PHP中使用strict_types进行类型转换

问题描述 投票:0回答:1

为什么此代码终止没有任何问题?我认为它会输出一个TypeError Exception,因为Integer不能被转换或转换为float的原因,因为strict_types的声明。

?php
declare(strict_types=1);
function multiply(float $a, float $b): float {
    return (double)$a * (double)$b;
}
$six = multiply(2, 3);
echo gettype($six);

//output: double
php casting type-conversion
1个回答
3
投票

可以基于每个文件启用严格模式。在严格模式下,只接受类型声明的确切类型的变量,否则将抛出TypeError。此规则的唯一例外是可以为期望浮点的函数赋予整数。

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict

这是allowed作为widening primitive conversion

扩展的原始转换不会丢失有关数值总体大小的信息。

© www.soinside.com 2019 - 2024. All rights reserved.