PHP ArgumentCountError

PHPServer Side ProgrammingProgramming

Introduction

PHP parser throws ArgumentCountError when arguments passed to a user defined function or method are less than those in its definition. ArgumentCountError class is inherited from TypeError class

ArgumentCountError Example

In Following example, a user defined function add() is defined to receive two arguments. However, if less than required number of arguments is provided while calling, ArgumentCountError will be thrown which can be handled with catch block.

Example

 Live Demo

<?php
function add($x, $y){
   return $x+$y;
}
try{
   echo add(10);
}
catch (ArgumentCountError $e){
   echo $e->getMessage();
}
?>

Output

This will produce following result −

Too few arguments to function add(), 1 passed in C:\xampp\php\test.php on line 6 and exactly 2 expected

In Following example, setdata() method in myclass is defined to have two formal arguments. When this method is called with less arguments, ArgumentCountException is thrown

Example

<?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();
}
?>

Output

This will produce following result −

Too few arguments to function myclass::setdata(), 0 passed in C:\xampp\php\test.php on line 15 and exactly 2 expected

ArgumentCountException is also thrown in case built-in function is given inappropriate or invalid number of arguments. However, strict-types mode must be set

Example

 Live Demo

<?php
declare(strict_types = 1);
try{
   echo strlen("Hello", "World");
}
catch (ArgumentCountError $e){
   echo $e->getMessage();
}
?>

Output

This will produce following result −

strlen() expects exactly 1 parameter, 2 given
raja
Published on 21-Sep-2020 15:07:53
Advertisements