How to use default arguments in php

I want to define a function doSomething(arg1, arg2)with default values ​​arg1 = val and arg2 = val

When I write

function doSomething($arg1="value1", $arg2="value2"){
 // do something
}

Is it now possible to call doSomething with arg1 and arg2 = "new_value2" by default

+3
source share
4 answers

No, unfortunately, this is not possible. If you define $arg2, you will also need to determine $arg1.

+5
source

Sometimes, if I have a lot of parameters with default settings, I will use an array to contain the arguments and combine it with the default values.

public function doSomething($requiredArg, $optional = array())
{
   $defaults = array(
      'arg1' => 'default',
      'arg2' -> 'default'
   );

   $options = array_merge($defaults, $optional);
}

It really only makes sense if you have a lot of arguments.

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

:

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

- arg1, arg2? , .

+2

Source: https://habr.com/ru/post/1745336/


All Articles