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"

liysd
  • 4,413
  • 13
  • 35
  • 38
  • C# 4.0 offers something similar called `Optional Parameters` move over to ASP.Net 4.0 ;) – Alex May 13 '10 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. – erisco May 13 '10 at 20:09

4 Answers4

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.

Bryan M.
  • 17,142
  • 8
  • 46
  • 60
5

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

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
3
function doSomething( $arg1, $arg2 ) {
  if( $arg1 === NULL ) $arg1 = "value1";
  if( $arg2 === NULL ) $arg2 = "value2";
  ...
}

And to call:

doSomething();
doSomething(NULL, "notDefault");
psychotik
  • 38,153
  • 34
  • 100
  • 135
  • 6
    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");` – Pekka May 13 '10 at 19:12
2

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

NatalieL
  • 91
  • 2