0

Here is my code:

function myfunc( $arg1, $arg2 = 'sth', $arg3 = 'sth else' ){
    // do stuff
}

Now I want to set a new value for arg3 and keep the default defined value for arg2. How can I do that?

Something like this:

myfunc( true, <keep everything defined as default>, $arg3 = 'new value' );

The expected result is sth in this fiddle.

stack
  • 10,280
  • 19
  • 65
  • 117

1 Answers1

3

A possible alternative would not have your function take 3 parameters, but only one, an array:

function my_function(array $value = array()) {
    // if set, use $value['key1']
    // if set, use $value['key2']
    // ...
}

And call that function like this:

my_function(array(
    'key1' => 'google',
    'key2' => 'yahoo'
));

This would allow you to:

  1. accept any number of parameters
  2. all of which could be optional

Hope it will helpful.

Md. Abutaleb
  • 1,590
  • 1
  • 14
  • 24