当传递给用户定义的函数或方法的参数小于其定义中的参数时,PHP分析器将引发ArgumentCountError。ArgumentCountError类从TypeError类继承
在以下示例中,用户定义的函数add()定义为接收两个参数。但是,如果调用时提供的参数数量少于要求的数量,则将引发ArgumentCountError,可以使用catch块进行处理。
<?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
在以下示例中,myclass中的setdata()方法被定义为具有两个形式参数。当使用较少参数调用此方法时,将引发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