在PHP 4/5中有可能在调用时跳过指定的可选参数(如在python中)吗?
就像是:
function foo($a,$b='', $c='') {
// whatever
}
foo("hello", $c="bar"); // we want $b as the default, but specify $c
谢谢
不,不可能:如果要传递第三个参数,则必须传递第二个参数。而命名参数也是不可能的。
“解决方案”将只使用一个参数,一个数组,并且始终通过它…但不要总是在其中定义所有内容。
例如 :
function foo($params) {
var_dump($params);
}
并以这种方式称之为:
foo(array(
'a' => 'hello',
));
foo(array(
'a' => 'hello',
'c' => 'glop',
));
foo(array(
'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可选参数? - 代码日志