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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP