PHP TypeError
简介
TypeError 类扩展Error类。如果实际参数类型和形式参数类型不匹配,返回的类型与声明的返回类型不匹配,或向任何内置函数传递无效参数,就会引发此错误
请注意strict_types应在脚本开头通过 declare()函数设置为 true −
在此示例中,形式变量和实际参数变量的类型不匹配,从而导致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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP