1

I have my own function called 'Parse' which is in an object 'Core', the function takes 5 parameters so far, each of which have default values [true,false].

Say if I wanted to change the 3rd parameter, but keep the rest the same, do I have to assign values to the rest or can I skip like so:

$Core->Parse(,,false,,);

Not sure if that makes sense to you or not. I just wanted to ask the question before I go ahead and do it. Or if that isn't possible, what other ways are there other than filling in the other parameter values, or are there none?

Any feedback would be great.

Thanks.

John Parker
  • 54,048
  • 11
  • 129
  • 129
Mark Eriksson
  • 1,455
  • 10
  • 19
  • 2
    Makes sense, but it's not possible – Pekka Aug 04 '13 at 20:14
  • 2
    With that many arguments you might as well use one array instead and only pass the non-defaults. – Ja͢ck Aug 04 '13 at 20:23
  • 1
    it seems that it didn't made it to PHP 5.5. [Skipping optional parameters for functions](https://wiki.php.net/rfc/skipparams) – bitWorking Aug 04 '13 at 20:25
  • In addition to the question @Pekka웃 mentions, you might also want to skim [Should my PHP functions accept an array of arguments or should I explicitly request arguments?](http://stackoverflow.com/questions/2112913/should-my-php-functions-accept-an-array-of-arguments-or-should-i-explicitly-requ/2112949#2112949) – John Parker Aug 04 '13 at 20:26

2 Answers2

0

This isn't possible via the usual technique of defining defaults within the function definition itself. (You can however omit all the args if there are defaults, or supply the initial arg and just the defaults for the subsequent ones.)

i.e.: Using...

function my_super_function($arg1='hello', $arg2='world') {
    // Do stuff
}

my_super_function(, 'mum');

...won't work.

However, there's nothing to stop you from checking for a valid default (using whatever criteria you wish) within the function itself.

For example:

function my_super_function($arg1='hello', $arg2='world') {
    $arg1 = $arg1 ? $arg1 : 'hello';

    // Do stuff
}

my_super_function(null, 'mum');
John Parker
  • 54,048
  • 11
  • 129
  • 129
0

you have to provide all parameters up to the one you want to set, if you dont need the first ones just use the default values that are listed in the definition of the function.

You could however make a shortcut method

class Core {
   ...
   public function shortParse($somevalue) {
     $this->Parse("param 1 default value",
                  "param 2 default value",
                  $somevalue,
                  "param 4 default value", //dont need the next 2
                  "param 5 default value");//if they have default values
   }
   ...
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87