liysd
liysd

Reputation: 4613

How to use default arguments in php

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"

Upvotes: 3

Views: 5215

Answers (4)

Bryan M.
Bryan M.

Reputation: 17322

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.

Upvotes: 8

NatalieL
NatalieL

Reputation: 91

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

Upvotes: 2

psychotik
psychotik

Reputation: 39019

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

And to call:

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

Upvotes: 3

Pekka
Pekka

Reputation: 449415

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

Upvotes: 5

Related Questions