PHP可选参数 - 按名称指定参数值? [英] PHP Optional Parameters - specify parameter value by name?
问题描述
我知道可以使用如下的可选参数:
函数doSomething($ do,$ something =something ){
}
doSomething(do);
doSomething(do,nothing);
但假设您有以下情况:
< pre $ 函数doSomething($ do,$ something =something,$ or =or,$ nothing =nothing){
}
doSomething(do,$ or =>and,$ nothing =>something);
所以在上面的行中它会默认 $ something
改为某些东西,尽管我正在设定其他值。我知道这在.net中是可行的 - 我一直都在使用它。但如果可能的话,我需要在PHP中执行此操作。
任何人都可以告诉我这是否可能吗?我正在修改我已经集成到Interspire购物车中的Omnistar联盟计划 - 所以我希望保持一个功能正常工作的地方,我不会改变对函数的调用,但在一个地方(我正在扩展)我想要指定其他参数。我不想创建另一个函数,除非我绝对必须。
不,在PHP中是不可能的。使用数组参数:
函数doSomething($ arguments = array()){
//设置默认值
$ arguments = array_merge(array(
argument=>default value,
),$ arguments);
var_dump($ arguments);
$ / code>
用法示例:
doSomething的(); //所有的默认值,或者:
doSomething(array(argument=>other value));
更改现有方法时:
<$ p $ b $函数doSomething($ bar,$ baz){
函数doSomething($ bar,$ baz,$ arguments = array()){
// $ bar和$ baz保持原位,旧代码工作
}
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.
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
}
这篇关于PHP可选参数 - 按名称指定参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!