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