PHP 参数计数错误


简介

如果传递给用户定义函数或方法的参数少于其定义中的参数,PHP 解析器将抛出参数计数错误。ArgumentCountError 类继承自TypeError

参数计数错误示例

在以下示例中,定义了一个用户定义函数 add() 来接收两个参数。但是,如果在调用时提供的参数数量少于所需数量,将会抛出参数计数错误,可以使用 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() 方法被定义为具有两个形式参数。当此方法使用较少参数调用时,将抛出参数计数异常

示例

<?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

如果内置函数给出的参数不合适或无效,也会抛出参数计数异常。但是,必须设置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

更新日期: 2020 年 9 月 21 日

448 次浏览

开启你的职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.