【问题标题】:Error while using declare for type restriction in PHP7 [duplicate]在 PHP7 中使用声明进行类型限制时出错 [重复]
【发布时间】:2023-03-17 12:38:01
【问题描述】:

我目前正在用小代码练习 PHP7。我正在使用这段代码来练习标量类型声明:

declare(strict_types=1);

function div(float $x, float $y)
{
    return $x / $y;
}

function sub(int $x, int $y)
{
    return $x - $y;
}

var_dump(div(2, 3.5)); // float(7)
var_dump(sub('2', 3)); // Fatal error: Uncaught TypeError: Argument 1 passed to sub() must be of the type integer, string given..

但是当我运行这段代码时,我的服务器给出了 500 错误。但是当我删除 declare() 时它可以工作。我的服务器正在运行 PHP7。

【问题讨论】:

  • '2' is string .. 错误很明显.. Strict type 正在验证类型:int - 2 和 string - '2'
  • 我的服务器没有运行这个脚本并给出 500 服务器错误
  • 这是您的服务器配置..检查显示错误以及如何启用它们..
  • 如何在 PHP7 中启用它们?
  • 谢谢我找到了方法:)

标签: php return-type declare


【解决方案1】:

使用声明(strict_types=1);你告诉 php 不要使用强制类型提示,所以你的字符串不会被转换为整数。 这就是你得到 TypeError 的原因。 如果您删除 declare(strict_types=1) php 使用强制类型提示,因此您的字符串将被转换为整数并且 php 不会抛出 TypeError。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多