Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP7中使用类型限制声明时出错_Php_Return Type_Declare - Fatal编程技术网

在PHP7中使用类型限制声明时出错

在PHP7中使用类型限制声明时出错,php,return-type,declare,Php,Return Type,Declare,我目前正在使用小代码练习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: Uncau

我目前正在使用小代码练习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。

使用declare(strict\u types=1);您告诉php不要使用强制类型提示,因此您知道字符串不会转换为整数。 这就是为什么会出现TypeError。
如果删除declare(strict_types=1),php将使用强制类型提示,这样字符串将转换为整数,php不会抛出类型错误。

'2'是字符串。。错误很明显。。Strict type正在验证以下类型:int-2和string-2“我的服务器未运行此脚本,并且在您的服务器配置中出现500个服务器错误。。检查显示错误以及如何启用它们..如何在PHP7中启用它们?谢谢我找到了方法:)