0

When I create a function that has optional parameters, I have to think about which one is more likely to be passed the most and that determines the order in which I specify them in the function declaration.

Take the below function with the not so well placed $mandatoryParam:

public function myFunc($mightBeEmptyA, $mightBeEmptyB, $mandatoryParam)
{

}

Is it better practice and would it be better to do the following?:

...
$this->myFunc(array('mightBeEmptyA' => 'myValue')) ;
...

public function myFunc($params)
{
    if($params['mightBeEmptyA'])
    {
        // Do something....
    }
}

Using an array to pass in parameters instead. Is the extra logic needed to process the parameters in the array worthwhile?

imperium2335
  • 23,402
  • 38
  • 111
  • 190
  • 1
    Maybe. It depends. If you're passing too many parameters, you should first look into whether you can simplify the function/parameters. – deceze Feb 25 '13 at 13:36

3 Answers3

0

Yes, if your function requires many arguments. For example a function that filters certain data, and you have many filters.

I usually do it like this:

public function myFunc(array $args){

  $args += array(
     'mightBeEmptyA' => 'defaultVal',
     // ...
  );

  extract($args, EXTR_SKIP);

  // and here I can use $mightBeEmptyA
}
nice ass
  • 16,471
  • 7
  • 50
  • 89
0

You should look at func_get_args this way it technically doesn't matter what you pass to the function you can sort it out within the function itself. You don't need to pass anything at all if you don't want to.

public function myFunc()
{
    if (func_num_args()) {
        // has arguments
        $arg_list = func_get_args();
        ...
    } else {
        // no arguments
    }
}
sjdaws
  • 3,466
  • 16
  • 20
0

You can use default parameters

public function myFunc( $mandatoryParam,$mightBeEmptyA="", $mightBeEmptyB="")
{

}

But if there is situation where your mightBeEmptyA should not be provided but mightBeEmptyB needs to be provided.Then you had call it like following

myFunc("mandatory","","OptionalB");

So take a call, based on your situation.

Jaydeep Rajput
  • 3,605
  • 17
  • 35