แนะนำตัว
TypeError คลาสขยาย ข้อผิดพลาด ระดับ. ข้อผิดพลาดนี้เกิดขึ้นเมื่อประเภทอาร์กิวเมนต์ที่แท้จริงและเป็นทางการไม่ตรงกัน ประเภทการส่งคืนไม่ตรงกับประเภทการส่งคืนที่ติดสติ๊กเกอร์ หรืออาร์กิวเมนต์ที่ไม่ถูกต้องส่งผ่านไปยังฟังก์ชันในตัว
โปรดทราบว่า strict_types ควรตั้งค่าเป็นจริงด้วยประกาศ() ฟังก์ชันที่ด้านบนของสคริปต์ −
ในตัวอย่างนี้ ประเภทของตัวแปรอาร์กิวเมนต์ที่เป็นทางการและจริงไม่ตรงกัน ส่งผลให้ 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
TypeError ยังถูกส่งออกไปเมื่อฟังก์ชันในตัวของ PHP ถูกส่งผ่านจำนวนอาร์กิวเมนต์ที่ไม่ถูกต้อง อย่างไรก็ตาม 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