3

I want to define a function doSomething(arg1, arg2) with default values to arg1=val and arg2=val

When I write

function doSomething($arg1="value1", $arg2="value2"){
 // do something
}

Is it possible now to call doSomething with default arg1 and arg2="new_value2"

2
  • C# 4.0 offers something similar called Optional Parameters move over to ASP.Net 4.0 ;) Commented May 13, 2010 at 19:11
  • 1
    Many languages offer something called named parameters where you could, as a PHP example, call doSomething($arg2="value2"). This is valid PHP syntax but do not be fooled into thinking it works as a named parameter. Commented May 13, 2010 at 20:09

4 Answers 4

8

Sometimes if I have a lot of parameters with defaults, I'll use an array to contain the arguments and merge it with defaults.

public function doSomething($requiredArg, $optional = array())
{
   $defaults = array(
      'arg1' => 'default',
      'arg2' -> 'default'
   );

   $options = array_merge($defaults, $optional);
}

Really only makes sense if you have a lot of arguments though.

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

Comments

5

Nope, sadly, this is not possible. If you define $arg2, you will need to define $arg1 as well.

Comments

3
function doSomething( $arg1, $arg2 ) {
  if( $arg1 === NULL ) $arg1 = "value1";
  if( $arg2 === NULL ) $arg2 = "value2";
  ...
}

And to call:

doSomething();
doSomething(NULL, "notDefault");

1 Comment

This is a nice workaround but using NULL to signify the default value may not be a good idea - after all, NULL could be a valid argument in itself. Another option would be to define a "default" constant containing something totally outlandish like ^^^^^^^-----DEFAULT----^^^^^^^^^^ to use instead. You could then doSomething(default, "notDefault");
2

Do you ever assign arg1 but not arg2? If not then I'd switch the order.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.