PHP ArgumentCountError

PHP throws ArgumentCountError when a function or method is called with fewer arguments than required in its definition. The ArgumentCountError class inherits from TypeError and can be caught using try-catch blocks.

Basic Function Example

Here's an example where a user-defined function add() expects two arguments but receives only one ?

<?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 and exactly 2 expected

Class Method Example

ArgumentCountError also occurs with class methods when insufficient arguments are provided ?

<?php
class MyClass {
    private $name;
    private $age;
    
    function setData($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

try {
    $obj = new MyClass();
    $obj->setData(); // Missing both arguments
} catch (ArgumentCountError $e) {
    echo $e->getMessage();
}
?>
Too few arguments to function MyClass::setData(), 0 passed and exactly 2 expected

Built-in Functions with Strict Types

When strict_types is enabled, ArgumentCountError is thrown for built-in functions with wrong argument counts ?

<?php
declare(strict_types = 1);

try {
    echo strlen("Hello", "World"); // strlen expects only 1 argument
} catch (ArgumentCountError $e) {
    echo $e->getMessage();
}
?>
strlen() expects exactly 1 parameter, 2 given

Conclusion

ArgumentCountError helps catch function call mistakes early by enforcing correct argument counts. Use try-catch blocks to handle these errors gracefully in your applications.

Updated on: 2026-03-15T09:24:16+05:30

605 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements