Why does PHP not throw an error when I pass too many parameters to a function?

Posted on

Why does PHP not throw an error when I pass too many parameters to a function? – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and function . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about Why does PHP not throw an error when I pass too many parameters to a function?.

I am a n00b at php. I was learning about Default Parameters so I made this function.

function doFoo($name = "johnny"){
    echo "Hello $name" . "<br />";

I made these calls

doFoo("ted", 22);

The first two printed what was expected i.e

Hello johnny
Hello ted

but the third call also printed

Hello ted

I was expecting an error, after all the function is made for one argument whereas I am calling it with two arguments.
Why was there no error?

Solution :

PHP doesn’t throw an error on function overload.

It is not wrong to pass more arguments to a function than needed.

You only get error if you pass to few arguments.

function test($arg1) {


Above will result in following error:
Uncaught ArgumentCountError: Too few arguments to function…

If you want to fetch first argument plus all others arguments passed to function you can do:

function test($arg1, ...$args) {
 var_dump($arg1, $args);

test('test1', 'test2', 'test3');

Resulting in:
string(5) “test1”
array(2) {
string(5) “test2”
string(5) “test3”

because PHP functions support variable number of parameters.

Apparently because that’s how PHP programmers like it. There was a String Argument Count RFC to emit a Notice when too many arguments are sent, but it was soundly rejected, to my dismay: https://wiki.php.net/rfc/strict_argcount

It should only print a notice, but no error.
I think you have your error reporting set up so that notices are not shown on screen.

Try pasting this at the top of your code:

error_reporting(E_ALL | E_STRICT);

Leave a Reply

Your email address will not be published. Required fields are marked *