0

So, this certainly not OK:

$this->callMe ($x, $y, $color, $method = 'default', $colordeep = '32')

This might be better:

$this->callMe (array('x' => $x, 'y' => $y, 'color' => $color))

But still, in this case I also have to look for the parameters always. Is there a better way to pass a large amount of parameters?

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
John Smith
  • 6,129
  • 12
  • 68
  • 123

1 Answers1

1

I run into this issue a lot. Especially with functions that for now only need three arguments, but may need as many as 10 later as I continue to develop. So:

function callMe($arguments = []){
    $defaults = ['x'=>1, 'y'=>2, 'awesome'=>true];
    defaultArray($arguments,$defaults);

    if($arguments['awesome'])
        return $arguments['x'] * $arguments['y'];

    return false;
}


function defaultArray(&$arguments = [], $defaults = []){
    if(!empty($defaults))
    foreach($defaults as $index=>$value){
        if(!isset($arguments[$index]))
            $arguments[$index] = $value;
    }
}

Something like this is my solution. I pass an array, and at the start of the function I just declare the defaults and then apply the two. You probably could use "array_merge" or something also, but I like the custom function because in the end I expand it to also have required fields, error messages and responses, etc.

Logan Bentley
  • 284
  • 1
  • 7
  • 1
    why not? It's a matter of taste. Since I know what I'm using it for, it just makes it simpler, as what I'm wanting to do with it in this particular case is to modify the array I'm passing, 100% of the time, just makes less code to write each time I implement it, if I was returning it etc. But, you totally can change it to not reference and just return the array. Just depends on your particular needs I'd say. – Logan Bentley Nov 29 '15 at 12:30
  • Fine solution, but I would offer two improvements. First, add a hint to arguments definition: `function callMe(array $arguments = [])`. Passing a string or something else instead of an array causes "Catchable fatal error". Second, the check of passed arguments should be done by `array_key_exists()`, not `isset()`. The difference explained in http://stackoverflow.com/questions/3210935/difference-between-isset-and-array-key-exists – Max Zuber Nov 29 '15 at 21:58