【问题标题】:'strict_types=1' does not seem to work in a function [duplicate]'strict_types = 1'似乎在函数中不起作用[重复]
【发布时间】:2018-01-10 02:11:50
【问题描述】:
<?php
declare(strict_types=1);
$a = 1;
$b = 2;
function FunctionName(int $a, int $b)
{
    $c = '10'; //string
    return $a + $b + $c;
}
echo FunctionName($a, $b);
?>

我预计FunctionName($a, $b) 会打印错误,但它不会打印错误消息。

如您所见,我在 int($a+$b) 中添加了一个字符串 ($c),并声明了 strict_types=1

为什么我收不到错误信息?

【问题讨论】:

  • declare(strict_types=1); 不可能
  • @AlivetoDie 你能解释一下为什么不可能吗?
  • 已在重复链接中给出:- stackoverflow.com/questions/37111470/…
  • @AlivetoDie 我认为您误解了您所链接的问题。该用户询问他们是否可以在所有文件中自动启用此指令(您不能);在一个文件的顶部启用它正是您可以做的,并且这个问题中的代码是完全有效的。

标签: php typing


【解决方案1】:

“严格类型”模式只检查代码中特定点的类型;它不会跟踪变量发生的所有事情。

具体来说,它会检查:

  • 给函数的参数,如果签名中包含类型提示;在这里,您将两个 ints 给一个期望两个 ints 的函数,所以没有错误
  • 函数的返回值,如果签名中包含返回类型提示;这里你没有类型提示,但是如果你有: int的提示,仍然不会出错,因为$a + $b + $c的结果确实是int

以下是一些确实会出错的例子:

declare(strict_types=1);
$a = '1';
$b = '2';
function FunctionName(int $a, int $b)
{
    return $a + $b;
}
echo FunctionName($a, $b);
// TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given

或返回提示:

declare(strict_types=1);
$a = 1;
$b = 2;
function FunctionName(int $a, int $b): int
{
    return $a . ' and ' . $b;
}
echo FunctionName($a, $b);
// TypeError: Return value of FunctionName() must be of the type integer, string returned

请注意,在第二个示例中,引发错误的不是我们计算 $a . ' and ' . $b 的事实,而是我们返回该字符串的事实,但我们的承诺是返回一个整数.以下将不会给出错误:

declare(strict_types=1);
$a = 1;
$b = 2;
function FunctionName(int $a, int $b): int
{
    return strlen( $a . ' and ' . $b );
}
echo FunctionName($a, $b);
// Outputs '7'

【讨论】:

  • 非常感谢。现在我理解得更清楚了。
猜你喜欢
  • 2013-06-19
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多