PHP 可选参数 - 按名称指定参数值?
我知道可以使用可选参数,如下所示:
function doSomething($do, $something = "something") {
}
doSomething("do");
doSomething("do", "nothing");
但假设您有以下情况:
function doSomething($do, $something = "something", $or = "or", $nothing = "nothing") {
}
doSomething("do", $or=>"and", $nothing=>"something");
因此,在上面的行中,即使我为所有内容设置值,它也会默认 $something
为“something”别的。我知道这在 .net 中是可能的 - 我一直使用它。但如果可能的话,我需要用 PHP 来做这件事。
谁能告诉我这是否可能?我正在更改已集成到 Interspire 购物车中的 Omnistar 联盟计划 - 因此我希望在任何我不更改函数调用的地方保持函数正常工作,但在一个地方(我正在扩展)我想要指定附加参数。除非绝对必要,否则我不想创建另一个函数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,在 PHP 中这是不可能的。使用数组参数:
用法示例:
更改现有方法时:
No, in PHP that is not possible as of writing. Use array arguments:
Example usage:
When changing an existing method:
看一下 func_get_args:https://www.php。 net/manual/en/function.func-get-args.php
Have a look at func_get_args: https://www.php.net/manual/en/function.func-get-args.php
命名参数当前在 PHP (5.3) 中不可用。
为了解决这个问题,您通常会看到一个函数接收参数
array()
,然后使用extract()
在局部变量或array_merge( )
默认它们。你原来的例子看起来像这样:
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 usingextract()
to use the supplied arguments in local variables orarray_merge()
to default them.Your original example would look something like:
PHP 没有命名参数。您必须决定一种解决方法。
最常见的是使用数组参数。但如果您只需要文字值,另一种聪明的方法是使用 URL 参数:
将此方法与默认参数结合起来,因为它适合您的特定用例。
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:
Combine this approach with default parameters as it suits your particular use case.