บทนำ
PHP parser โยน ArgumentCountError เมื่อ arguments ที่ส่งให้ user-defined function หรือ method น้อยกว่าที่กำหนดใน definition คลาส ArgumentCountError สืบทอดมาจากคลาส TypeError
ArgumentCountError Example
ในตัวอย่างต่อไปนี้ ฟังก์ชัน user-defined add() ถูกกำหนดให้รับ 2 arguments แต่หากเรียกด้วย arguments น้อยกว่าที่ต้องการ 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 ถูกกำหนดให้มี 2 formal arguments เมื่อเรียกเมธอดนี้ด้วย arguments น้อยกว่า 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 ยังถูกโยนเมื่อ built-in function ได้รับ arguments ที่ไม่เหมาะสมหรือจำนวนไม่ถูกต้อง อย่างไรก็ตาม ต้องตั้งค่า strict-types mode
ตัวอย่าง
<?php declare(strict_types = 1); try{ echo strlen("Hello", "World"); } catch (ArgumentCountError $e){ echo $e->getMessage(); } ?>ผลลัพธ์
จะได้ผลลัพธ์ดังนี้
strlen() expects exactly 1 parameter, 2 given