Occasionally I’ll write a PHP function with a single input, an associative array containing all of that function’s inputs. This has benefits such as not having to remember the correct order of inputs, but I’ve also noticed it makes implementing changes to large codebases much easier; when I need to add another variable, and that variable has to pass through 4 or 5 pre-existing functions, it’s much easier when I can just stick it in the array and pass it along.
My question is, is there a downside to doing this?
I rarely see functions written this way in examples, or in open source I use, which leads me to believe there is probably a downside. If there isn’t a reason not to do it then why not write all functions this way?
UPDATE
Thanks for all your answers. It looks like two major problems stand out:
Code readability – impossible to tell what variables are going into a function and what they’re for
Variable creep – Could wind up with massive arrays bouncing from one function to the next; one should not pass parameters to functions that don’t require them
Which are both great points I did not think about.
It seems the general gist as well is that code where this is an issue, should probably be converted to a class. Unfortunately in this specific project such a refactoring is beyond the scope, but I also think Bill Karwin’s solution is good – pass an array of optional variables
For that matter, why not forget about parameters completely, and use global variables for everything? (kidding)
Passing an associative array has one useful advantage: you can make multiple function parameters optional, and you can pass a value for the Nth parameter without having to pass a value for the *N-1*th parameter.
But you have no way to make mandatory parameters with a compile-time error if you don’t pass them. Neither can you declare type-checking.
You’ll have to write code inside the called function to check for the presence and the type of required parameters.
An alternative I have used is to declare conventional parameters for those that are mandatory, and then as the last (optional) argument, declare an associative array called
$optionsthat contains only the optional items.