Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Optional Parameters - specify parameter value by name?

I know it is possible to 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 it would default $something to "something", even though I am setting 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.

Can anyone tell me if this is possible? I am altering the Omnistar Affiliate program which I have integrated into Interspire Shopping Cart - so I want to keep a function working as normal for any places where I dont change the call to the function, but in one place (which I am extending) I want to specify additional parameters. I dont want to create another function unless I absolutely have to.

like image 317
ClarkeyBoy Avatar asked Oct 27 '10 01:10

ClarkeyBoy


People also ask

How do you specify an optional parameter?

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.

Does PHP support named parameters?

In PHP 8.0, Named Parameters support is added, which means it's now possible to call a function/method by setting the parameters by their name.

Where the default value of a parameter have to be specified?

Default parameter values must appear on the declaration, since that is the only thing that the caller sees.


1 Answers

No, in PHP that is not possible as of writing. Use array arguments:

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

    var_dump($arguments);
}

Example usage:

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

When changing an existing method:

//function doSomething($bar, $baz) {
function   doSomething($bar, $baz, $arguments = array()) {
    // $bar and $baz remain in place, old code works
}
like image 69
sanmai Avatar answered Sep 21 '22 02:09

sanmai