Giới thiệu
Lớp TypeError kế thừa Error. Lỗi ném khi kiểu đối số thực tế và hình thức không khớp, kiểu trả về không khớp khai báo, hoặc đối số không hợp lệ truyền cho hàm tích hợp.
Lưu ý strict_types phải bật true bằng declare() đầu script.
Ví dụ: kiểu tham số hình thức và thực tế không khớp, gây TypeError.
Ví dụ
<?php function add(int $first, int $second) { echo "addition: " . $first + $second; } try { add('first', 'second'); } catch (TypeError $e) { echo $e->getMessage(), "\n"; } ?>Kết quả:
Kết quả
Argument 1 passed to add() must be of the type integer, string given, called in C:\xampp\php\test.php on line 9
Ví dụ: hàm user nên trả integer nhưng trả array, gây TypeError:
Ví dụ
<?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"; } ?>Kết quả
Return value of myfunction() must be of the type integer, array returned
TypeError cũng ném khi hàm tích hợp nhận sai số đối số. Cần strict_types=1 đầu script:
Ví dụ
<?php declare(strict_types = 1); try { echo pow(100, 2, 3); } catch (TypeError $e) { echo $e->getMessage(), "\n"; } ?>Kết quả
pow() expects exactly 2 parameters, 3 given