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.

9
  • as per your fiddle you haven't defined $arg2 before calling that function Commented Jul 5, 2017 at 6:05
  • your question is not clear please add some more explanation. Commented Jul 5, 2017 at 6:05
  • @YaseenAhmed I want to set a value for arg3 without setting any value for arg2. As you see both arg3 and arg2 are optional. And I want to use the defined default value for arg2. Commented Jul 5, 2017 at 6:07
  • you can use array as argument and set the value inside function if not found. Commented Jul 5, 2017 at 6:07
  • @stack Do you want this ? 3v4l.org/RntQ9 Commented Jul 5, 2017 at 6:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.