在 PHP 中是否可以在调用函数/方法时指定命名的可选参数,跳过您不想指定的参数(如在 python 中)?
类似于:
function foo($a, $b = '', $c = '') {
// whatever
}
foo("hello", $c="bar"); // we want $b as the default, but specify $c
最佳答案
不,不可能( before PHP 8.0 ):如果要传递第三个参数,则必须传递第二个参数。并且命名参数也是不可能的。
“解决方案”是只使用一个参数,一个数组,并始终传递它……但不要总是定义其中的所有内容。
例如:
function foo($params) {
var_dump($params);
}
这样调用它:(键/值数组)
foo([
'a' => 'hello',
]);
foo([
'a' => 'hello',
'c' => 'glop',
]);
foo([
'a' => 'hello',
'test' => 'another one',
]);
会给你这个输出:
array
'a' => string 'hello' (length=5)
array
'a' => string 'hello' (length=5)
'c' => string 'glop' (length=4)
array
'a' => string 'hello' (length=5)
'test' => string 'another one' (length=11)
但我不太喜欢这个解决方案:
- 您将丢失 phpdoc
- 您的 IDE 将无法再提供任何提示......这很糟糕
所以我只会在非常特殊的情况下使用它——例如,对于具有大量可选参数的函数......
关于php - PHP 是否允许命名参数以便可以在函数调用中省略可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1342908/