views:

191

answers:

4

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"

+1  A: 

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

Pekka
+1  A: 
function doSomething( $arg1, $arg2 ) {
  if( $arg1 === NULL ) $arg1 = "value1";
  if( $arg2 === NULL ) $arg2 = "value2";
  ...
}

And to call:

doSomething();
doSomething(NULL, "notDefault");
psychotik
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
A: 

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

NatalieL
+2  A: 

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.