'strict_types = 1'似乎在某个功能中不起作用
问题描述:
<?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
。'strict_types = 1'似乎在某个功能中不起作用
为什么我不能收到错误信息?
答
“严格类型”模式只检查代码中特定点的类型;它不会跟踪变量发生的所有事情。
具体而言,它会检查:
- 给该函数的参数,如果类型提示被包括在签名;这里给出了两个函数
int
到一个函数,期望两个int
s,所以没有错误 - 函数的返回值,如果返回类型提示包含在签名中;在这里你没有类型提示,但如果你有暗示
: 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'
+0
非常感谢。现在我更清楚地理解它了。 – Saturn
'声明(strict_types = 1);'不可能 –
@AlivetoDie你能解释我为何不可以? – Saturn
已经在重复链接中给出: - https://stackoverflow.com/questions/37111470/enabling-strict-types-globally-in-php-7 –