แนะนำตัว
PHP parser ส่ง ArgumentCountError เมื่ออาร์กิวเมนต์ส่งผ่านไปยังฟังก์ชันหรือเมธอดที่ผู้ใช้กำหนดน้อยกว่าที่กำหนดไว้ในคำจำกัดความ ArgumentCountError คลาสนั้นสืบทอดมาจาก TypeError คลาส
ตัวอย่าง ArgumentCountError
ในตัวอย่างต่อไปนี้ ผู้ใช้กำหนดฟังก์ชัน add() ถูกกำหนดให้รับสองอาร์กิวเมนต์ อย่างไรก็ตาม หากมีการระบุจำนวนอาร์กิวเมนต์น้อยกว่าที่ต้องการขณะโทร ArgumentCountError จะถูกส่งออกไป ซึ่งสามารถจัดการกับ catch block ได้
ตัวอย่าง
<?php
function add($x, $y){
return $x+$y;
}
try{
echo add(10);
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?> ผลลัพธ์
สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้ -
Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 6 and exactly 2 expected
ในตัวอย่างต่อไปนี้ setdata() เมธอดใน myclass ถูกกำหนดให้มีอาร์กิวเมนต์ที่เป็นทางการสองข้อ เมื่อวิธีนี้ถูกเรียกโดยมีอาร์กิวเมนต์น้อยกว่า ArgumentCountException จะถูกส่งออกไป
ตัวอย่าง
<?php
class myclass{
private $name;
private $age;
function setdata($name, $age){
$this->name=$name;
$this->age=$age;
}
}
try{
$obj=new myclass();
obj->setdata();
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?> ผลลัพธ์
สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้ -
Too few arguments to function myclass::setdata(), 0 passed in C:\xampp\php\test.php on line 15 and exactly 2 expected
ArgumentCountException ยังถูกส่งออกไปในกรณีที่ฟังก์ชันในตัวได้รับจำนวนอาร์กิวเมนต์ที่ไม่เหมาะสมหรือไม่ถูกต้อง อย่างไรก็ตาม ประเภทเข้มงวด ต้องตั้งค่าโหมด
ตัวอย่าง
<?php
declare(strict_types = 1);
try{
echo strlen("Hello", "World");
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?> ผลลัพธ์
สิ่งนี้จะทำให้เกิดผลลัพธ์ดังต่อไปนี้ -
strlen() expects exactly 1 parameter, 2 given