Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP TypeError

บทนำ

คลาส TypeError extends คลาส Error ข้อผิดพลาดนี้เกิดขึ้นเมื่อ actual และ formal argument types ไม่ตรงกัน return type ไม่ตรงกับ declared return type หรือส่ง invalid arguments ให้ built-in function ใดๆ

โปรดทราบว่า strict_types ควรตั้งเป็น true ด้วยฟังก์ชัน declare() ที่ด้านบนของ script

ในตัวอย่างนี้ types ของ formal และ actual argument variables ไม่ตรงกัน ทำให้เกิด 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

ในตัวอย่างต่อไป ฟังก์ชัน user-defined ควรคืนค่า integer แต่คืนค่า array แทน ทำให้เกิด 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 ยังถูกโยนเมื่อ built-in function ของ PHP ได้รับจำนวน arguments ไม่ถูกต้อง อย่างไรก็ตาม directive 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