PHP Optional parameters - specify parameter value by name?

I know that you can use optional arguments as follows:

function doSomething($do, $something = "something") {

}

doSomething("do");
doSomething("do", "nothing");

But suppose you have the following situation:

function doSomething($do, $something = "something", $or = "or", $nothing = "nothing") {

}

doSomething("do", $or=>"and", $nothing=>"something");

So, in the above line, the default will be $something“something”, although I set the values ​​for everything else. I know this is possible in .net - I use it all the time. But I need to do this in PHP, if possible.

- , ? Omnistar, Interspire, , , , ( ) . , .

+5
4

, PHP . :

function doSomething($arguments = array()) {
    // set defaults
    $arguments = array_merge(array(
        "argument" => "default value", 
    ), $arguments); 

    var_dump($arguments);
}

:

doSomething(); // with all defaults, or:
doSomething(array("argument" => "other value"));

:

//function doSomething($bar, $baz) {
function   doSomething($bar, $baz, $arguments = array()) {
    // $bar and $baz remain in place, old code works
}
+11

PHP (5.3).

, , array(), extract(), array_merge() .

:

$args = array('do' => 'do', 'or' => 'not', 'nothing' => 'something');
doSomething($args);
+2

PHP . .

. URL, :

 function with_options($any) {
      parse_str($any);    // or extract() for array params
 }

 with_options("param=123&and=and&or=or");

, .

0

All Articles