PHP Optional Parameters - specify parameter value by name?

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

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.

回答1:

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 } 


回答2:

Have a look at func_get_args: http://au2.php.net/manual/en/function.func-get-args.php



回答3:

Named arguments are not currently available in PHP (5.3).

To get around this, you commonly see a function receiving an argument array() and then using extract() to use the supplied arguments in local variables or array_merge() to default them.

Your original example would look something like:

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


回答4:

PHP has no named parameters. You'll have to decide on one workaround.

Most commonly an array parameter is used. But another clever method is using URL parameters, if you only need literal values:

 function with_options($any) {       parse_str($any);    // or extract() for array params  }   with_options("param=123&and=and&or=or"); 

Combine this approach with default parameters as it suits your particular use case.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!