开发者

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开发者_StackOverflow中文版 and arg2="new_value2"


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜