PHP中的命名函数参数 [英] Named function parameters in PHP
问题描述
在php
中是否像python
中那样具有命名的函数参数?一个示例用例是:
Is it possible in php
like in python
to have named function parameters? An example use case is:
function foo($username = "", $password = "", $timeout = 10) {
}
我要覆盖$timeout
:
foo("", "", 3);
丑陋.我宁愿这样做:
foo(timeout=3);
推荐答案
否,PHP中无法使用命名参数.从技术上讲,当您调用foo($timeout=3)
时,它将首先对$timeout=3
求值,结果为3
并将其作为第一个参数传递给foo()
.而且PHP强制执行参数顺序,因此可比调用必须为foo("", "", $timeout=3)
.您还有两个选择:
No, named parameters are not possible in PHP. Technically when you call foo($timeout=3)
it is evaluating $timeout=3
first, with a result of 3
and passing that as the first parameter to foo()
. And PHP enforces parameter order, so the comparable call would need to be foo("", "", $timeout=3)
. You have two other options:
- 让函数将数组作为参数并检查数组键.我个人觉得这很丑,但是它可以工作并且可读.好处是简单,以后添加新参数很容易.缺点是您的函数缺乏自我记录功能,并且不会从IDE(自动完成,快速的函数参数查找等)中获得很多帮助.
- 设置不带参数的函数,并使用
func_get_args()
或使用...
可变长度参数功能.根据参数的数量,您可以决定如何对待每个参数.许多JQuery函数都执行类似的操作.这很容易,但是对于那些调用您的函数的人来说可能会造成混淆,因为它也不是自记录的.而且您的论点仍未命名.
- Have your function take an array as parameter and check the array keys. I personally find this ugly but it works and is readable. Upside is simplicity and it's easy to add new parameters later. Downside is your function is less self-documenting and you won't get much help from IDEs (autocomplete, quick function param lookups, etc.).
- Set up the function with no parameters and ask PHP for the arguments using
func_get_args()
or use the...
variable length arguments feature in PHP 5.6+. Based on the number of parameters you can then decide how to treat each. A lot of JQuery functions do something like this. This is easy but can be confusing for those calling your functions because it's also not self-documenting. And your arguments are still not named.
请注意,还有一个用于命名参数的RFC 仍在讨论中".
Note there is an RFC for named parameters still "under discussion".
这篇关于PHP中的命名函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!