PHP ArgumentCountError
phpserver side programmingprogramming更新于 2025/7/18 11:52:17
简介
当传递给用户定义函数或方法的参数少于其定义中的参数数量时,PHP 解析器会抛出 ArgumentCountError 错误。ArgumentCountError 类继承自 TypeError 类
ArgumentCountError 示例
在以下示例中,用户定义函数 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 异常。但是,必须设置 strict-types 模式。
示例
<?php
declare(strict_types = 1);
try{
echo strlen("Hello", "World");
}
catch (ArgumentCountError $e){
echo $e->getMessage();
}
?>
输出
这将产生以下结果 −
strlen() expects exactly 1 parameter, 2 given

