PHP TypeError
介绍
TypeError 类扩展了Error类。当实际参数和形式参数类型不匹配,返回类型与不合法的返回类型或传递给任何内置函数的无效参数不匹配时,将引发此错误
请注意,应该使用脚本顶部的define ()函数将strict_types设置为true:
在此示例中,形式参数和实际参数变量的类型不匹配,从而导致TypeError。
示例
<?php
function add(int $first, int $second){
echo "addition: " . $first + second;
}
try {
add('first', 'second');
}
catch (TypeError $e) {
echo $e->getMessage(), "\n";
}
?>这将产生以下结果-
输出结果
Argument 1 passed to add() must be of the type integer, string given, called in C:\xampp\php\test.php on line 9
在下面的示例中,用户定义的函数应该返回整数数据,而是返回一个数组,这将导致TypeError
示例
<?php
function myfunction(int $first, int $second): int{
return array($first,$second);
}
try {
$val=myfunction(10, 20);
echo "returned data : ". $val;
}
catch (TypeError $e) {
echo $e->getMessage(), "\n";
}
?>输出结果
这将产生以下结果-
Return value of myfunction() must be of the type integer, array returned
当PHP的内置函数传递了错误数量的参数时,也会引发TypeError。但是,必须在开头设置strict_types=1指令
示例
<?php
declare(strict_types=1);
try{
echo pow(100,2,3);
}
catch (TypeError $e) {
echo $e->getMessage(), "\n";
}
?>输出结果
这将产生以下结果-
pow() expects exactly 2 parameters, 3 given
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短