【问题标题】:type conversion with strict_types in PHP在 PHP 中使用 strict_types 进行类型转换
【发布时间】:2018-07-03 14:44:42
【问题描述】:

为什么这段代码会毫无问题地终止? 我认为它会输出 TypeError 异常,因为 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】:

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

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

    allowedwidening primitive conversion

    加宽基元转换不会丢失有关数值整体大小的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多