PHP Function Arguments: Parameters or Array?

A discussion on Reddit raised this question: Is it better to pass arguments into a PHP function or method via multiple parameters, or via an a single array?

The answer, in my humble opinion, is: it depends. 

Readability

There are a wide variety of factors that play into this argument that all have merit and validity.  The first is readability.   If you ever sacrifice readability to save a couple of bytes of data, please comment your name and address below so I can come to your house and hit you upside the head with the Gang of Four.  If someone cannot read your code, then you've failed at half of what being a programmer is.  Usually a method with poor readability is passed like so:

  1. // Bad code. What is arg?
  2. function my_function($arg1, $arg2, $arg3) {
  3.  
  4. }
  5.  
  6. // Equally bad. What's an array of args? What's an arg?
  7. function my_function($array_of_args) {
  8.  
  9. }

What does the above accomplish? Nothing. So make sure you get this right first.

Evolution

Code evolves. New features become available. New code needs to be written. If you didn't have the foresight to see that your functions might one day change is pretty much bad coding. So if a function is written well, but must maintain backward compatibility, you have to either wrap your old function in a new one, or essentially grow out your argument list to an insane degree.

  1. // This was ok in 1.0
  2. function my_function($type, $version, $name) {
  3. // do stuff
  4. }
  5.  
  6. // but now it's version 6 and your function looks like this
  7. function my_function($type, $version, $name, $dep, $location, $alias, $required, $return) {
  8. // For real?
  9. }

Bottom Line

I could easily go on for days with examples of one direction or the other, but it boils down to this.

  • Never make any argument list more than 3 (I even will give the occasional exception to 4)
  • If at any time an argument is optional, make sure its AFTER the the required arguments.
  • Consider making all functions pass arrays for maximum flexibility.
  • Make any and all expansion into further arguments as your code evolves an array for maximum flexibility.

This entry was posted in Development on by .

About Ryan Street

Ryan Street is a Plus Certified Magento Developer who loves everything related to Magento, WordPress, PHP, and programming. When not turning coffee into code, he is usually spotted somewhere online answering questions and helping people.

Leave a Reply