
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
PHP ArgumentCountError
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
<?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
<?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
- Related Articles
- PHP php://
- Upload file with php to another php server
- PHP Generators.
- PHP Overloading
- PHP Traits
- PHP $_GET
- PHP $GLOBALS
- PHP $_SERVER
- PHP superglobals
- PHP References
- PHP Constants
- PHP Expressions
- PHP Tags
- PHP Iterables
- PHP NULL
