Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my PHP functions accept an array of arguments or should I explicitly request arguments?

In a PHP web application I'm working on, I see functions defined in two possible ways.

Approach 1:

function myfunc($arg1, $arg2, $arg3) 

Approach 2:

// where $array_params has the structure array('arg1'=>$val1, 'arg2'=>$val2, 'arg3'=>$val3) function myfunc($array_params) 

When should I use one approach over another? It seems that if system requirements keep changing, and therefore the number of arguments for myfunc keep changing, approach 1 may require a lot of maintenance.

like image 668
John Avatar asked Jan 21 '10 21:01

John


People also ask

Why should a function that accepts an array as an argument?

Terms in this set (78) Why should a function that accepts an array as an argument, and processes that array, also accept an argument specifying the array's size? In order to process array in function, passing array alone cannot determine the number of elements in array, therefore we need array size argument also.

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);

Can a function take an array as an argument?

If we pass an entire array to a function, all the elements of the array can be accessed within the function. Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function.

How many arguments can a PHP function have?

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


1 Answers

If the system is changing so often that using an indexed array is the best solution, I'd say this is the least of your worries. :-)

In general functions/methods shouldn't take too many arguments (5 plus or minus 2 being the maximum) and I'd say that you should stick to using named (and ideally type hinted) arguments. (An indexed array of arguments only really makes sense if there's a large quantity of optional data - a good example being configuration information.)

As @Pekka says, passing an array of arguments is also liable to be a pain to document and therefore for other people/yourself in 'n' months to maintain.

Update-ette...

Incidentally, the oft mentioned book Code Complete examines such issues in quite a bit of detail - it's a great tome which I'd highly recommend.

like image 61
John Parker Avatar answered Sep 21 '22 05:09

John Parker