PHP TypeError

phpserver side programmingprogramming更新于 2025/8/19 5:37:17

简介

TypeError类扩展了Error类。当实际参数类型与形式参数类型不匹配、返回类型与声明的返回类型不匹配,或者传递给任何内置函数的参数无效时,都会引发此错误。

请注意,应将strict_types设置为 true,并在脚本顶部使用declare()函数。

在此示例中,形式参数变量和实际参数变量的类型不匹配,导致TypeError。

示例

<?php
function add(int $first, int $second){
   echo "addition: " . $first + second;
}
try {
   add('first', 'second');
}
catch (TypeError $e) {
   echo $e->getMessage(), "
"; } ?>

这将产生以下结果 −

输出

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(), "
"; } ?>

输出

这将产生以下结果 −

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(), "
"; } ?>

输出

这将产生以下结果 −

pow() expects exactly 2 parameters, 3 given

相关文章