Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(); doFoo("ted"); 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?

like image 522
prometheuspk Avatar asked Oct 28 '11 11:10

prometheuspk


People also ask

How many parameters can a function have in PHP?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments.

Can a function have too many parameters?

You can define as many parameters as you may need, but too many of them will make your routine difficult to understand and maintain. Of course, you could use a structured variable as a workaround: putting all those variables in a single struct and passing it to the routine.

Can we pass function as a parameter in PHP?

There is another type of function known as PHP Parameterized functions, these are the functions with pre defined parameters. You'll pass any number of parameters inside a function. These passed parameters act as variables in your function. They are declared inside the brackets, after the function name.

Can we pass array as argument in PHP?

You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... } sendemail(array('a', 'b', 'c'), 10);


2 Answers

PHP doesn't throw an error on function overload.

like image 155
Tom Avatar answered Sep 22 '22 00:09

Tom


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) {  var_dump($arg1); }  test(); 

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) { [0]=> string(5) "test2" [1]=> string(5) "test3" }

like image 40
jamietelin Avatar answered Sep 26 '22 00:09

jamietelin