Question

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"

Was it helpful?

Solution

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

OTHER TIPS

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.

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

And to call:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top