PHP严格类型检查模式

前言

PHP默认情况下是弱类型校验模式,在php7下declare新增了strict_types指令,通过设置strict_types的值(1或者0),1表示严格类型校验模式,作用于函数调用和返回语句;0表示弱类型校验模式。
严格类型检查模式猜测是为php8的jit做好铺垫.

注意:declare(strict_types=1)必须是文件的第一个语句。如果这个语句出现在文件的其他地方,将会产生一个编译错误,块模式是被明确禁止的。

示例

  • 没开启严格类型检查模式
<?php
/*
 * 输入数字 传出数字
 */
function test(int $num): int
{
    return $num;
}

echo test(1); // 1

echo test(false); // 0

可以看出定义传入参数必须是int类型,传入false竟然没报错,但是坑爹的是php竟然自动进行了类型装换.这种就是隐形的BUG!!

  • 开启严格类型检查模式
<?php
declare(strict_types=1);//必须为第一个语句

function test(int $num): int
{
    return $num;
}

echo test(false);

//此时会报错,参数必须为整型
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type integer, boolean given

参考资料

原文地址:https://www.cnblogs.com/liuyublog/p/9623300.html