php如何理解严格模式declare(strict_types=1)?

2025年4月9日 8点热度 0人点赞 0条评论

严格模式的写法:

PHP

decleare(strict_type=1);

严格模式的声明需要放到php文件的最顶端,否则会抛出错误:

Fatal error: strict_types declaration must be the very first statement in the script

这个声明的类型属于是没有错误去制造错误,主要就是检测变量的类型type,如果不对,就会报错。值得特别说明的是:如果没有定义严格模式的话,这些类型错误很有可能都是可以接受的,并不会报错。

For example:

<?php
function add(int $a, int $b):int{    
    return $a + $b;
}
var_dump(add(1.0, 2.0));

在此状态下执行独立时,输出int(3)

我们提供的是double类型,但php7能很好的处理它,和php5时代没什么区别

做了如下变更

<?php
declare(strict_types=1);    //加入这句

function add(int $a, int $b): int
{
    return $a + $b;
}

var_dump(add(1.0, 2.0));

TypeError产生,如下

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given, called in /Users/hiraku/sandbox/stricttypes/A.php on line 9 and defined in /Users/hiraku/sandbox/stricttypes/A.php:4Stack trace:
#0 /Users/hiraku/sandbox/stricttypes/A.php(9): add(1, 2)
#1 {main}
  thrown in /Users/hiraku/sandbox/stricttypes/A.php on line 4

MuWinds

这个人很懒,什么都没留下

文章评论