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

更新時間:2020 年 9 月 21 日

217 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.