ভূমিকা
TypeError ক্লাস Error ক্লাস এক্সটেন্ড করে। এই এরর উত্থাপন হয় যখন একচুয়াল এবং ফরম্যাল আর্গুমেন্ট টাইপ ম্যাচ না করে, রিটার্ন টাইপ ডিক্লেয়ার্ড রিটার্ন টাইপের সাথে ম্যাচ না করে বা কোনো বিল্ট-ইন ফাংশনে অবৈধ আর্গুমেন্ট পাস করা হয়।
মনে রাখবেন strict_types ট্রু সেট করা উচিত declare() ফাংশন দিয়ে স্ক্রিপ্টের শুরুর দিকে—
এই উদাহরণে, ফরম্যাল এবং একচুয়াল আর্গুমেন্ট ভেরিয়েবল টাইপ ম্যাচ না করলে 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