John Smith
John Smith

Reputation: 6197

Ideas how to pass large amount of parameters to method?

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?

Upvotes: 0

Views: 167

Answers (1)

Logan Bentley
Logan Bentley

Reputation: 274

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.

Upvotes: 1

Related Questions