Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP passing array to function

Tags:

function

php

I've seen a few people ask a similar question. But I do need a little more clarification on this particular subject.

I have several functions that pass several arguments. I even have a few that are about 10 arguments. (didn't initially plan it, simply grew over time)

I don't have any problems looking at my source code to find out what the 7th argument is, but it does get tedious. Most of the time I know what arguments to pass, just not the position.

I had a few ideas to simplify the process for me.

a) pass 1 argument, but divide everything with some delimiter. (but that's a bad idea!, since I still need to remember the position of each.

function myfunc('data|data|data|'){
          // explode the string
}

b) pass an array with key and values, and look for the key names inside my function, and act accordingly.

function myfunc(array('arg1' => 'blah blah', 'arg2' => 'more blah')){
  // loop through the array
}

c) keep it as it is.

function myfunc($arg1,$arg2,$arg3,$arg4,$arg5........){
// yay

}

So, I'm seeking other options and better ideas for handling functions with growing argument lists.

like image 900
coffeemonitor Avatar asked Dec 12 '22 09:12

coffeemonitor


1 Answers

In my opinion, the best way to it is by passing in an associative array. That way you immediately see what each argument does. Just be sure to name them descriptively, not arg1 & arg2.

Another advantage an associative array, is that you don't have to care about the order in which the arguments are being passed in.

Just remember that if you use an associative array, you lose PHP's native way of assigning default values, e.g.:

function doSomething($arg1 = TRUE, $arg2 = 55) { }

So, what you have to do is create your own set of default options, and then merge your arrays:

function doSomething( $props = array() )
{
    $props = array_merge(array(
        'arg1' => TRUE,
        'arg2' => 55
    ), $props);

    // Now use the $props array
}
like image 176
Joseph Silber Avatar answered Dec 27 '22 15:12

Joseph Silber