PHP开启强类型检验

PHP是世界上最好的语言,开发快是它最大的优势,凡事有利必有弊。

众所周知,PHP是弱类型语言,在传递参数时,不会检查变量的类型,再加上动态语言的特性,如果写代码不注意,很容易造成类型不符,自动转换类型,并且程序不会报错,造成数据错误和不完整。

在PHP7之后,通过在文件开头用 declare(strict_types = 1) 定义强类型检验后,当函数传参类型不符时,将会抛出错误。

开启类型检验之前:

<?php
//declare(strict_types = 1);

function sum(int $a, int $b){
    return $a + $b;
}
$a = '1';
$b = '2';
echo sum($a, $b);
[Running] php "/Users/why/Desktop/php/why.php"
3
[Done] exited with code=0 in 0.3 seconds

开启类型检验之后:

<?php
declare(strict_types = 1);

function sum(int $a, int $b){
    return $a + $b;
}
$a = '1';
$b = '2';
echo sum($a, $b)
[Running] php "/Users/why/Desktop/php/why.php"
PHP Fatal error:  Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, string given, called in /Users/why/Desktop/php/why.php on line 9 and defined in /Users/why/Desktop/php/why.php:4
Stack trace:
#0 /Users/why/Desktop/php/why.php(9): sum('1', '2')
#1 {main}
  thrown in /Users/why/Desktop/php/why.php on line 4

[Done] exited with code=255 in 0.325 seconds
发布了226 篇原创文章 · 获赞 31 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/104399661