在PHP 4/5中是否可以在调用时指定一个命名的可选参数,跳过你不想指定的参数(比如在python中)?
就像是:
function foo($a,$b='', $c='') {
// whatever
}
foo("hello", $c="bar"); // we want $b as the default, but specify $c
Run Code Online (Sandbox Code Playgroud)
谢谢
是否有可能在php像python有一个名为函数参数?一个示例用例是:
function foo($username = "", $password = "", $timeout = 10) {
}
Run Code Online (Sandbox Code Playgroud)
我想覆盖$timeout:
foo("", "", 3);
Run Code Online (Sandbox Code Playgroud)
丑陋.我宁愿这样做:
foo(timeout=3);
Run Code Online (Sandbox Code Playgroud) 在PHP中,您可以调用函数.通过使用这些语句不调用所有参数.
function test($t1 ='test1',$t2 ='test2',$t3 ='test3')
{
echo "$t1, $t2, $t3";
}
Run Code Online (Sandbox Code Playgroud)
你可以使用这样的功能
test();
Run Code Online (Sandbox Code Playgroud)
所以我只想说我希望最后一个是不同的而不是其他的.我能做到的唯一方法是做到这一点,但没有成功:
test('test1','test2','hi i am different');
Run Code Online (Sandbox Code Playgroud)
我试过这个:
test(,,'hi i am different');
test(default,default,'hi i am different');
Run Code Online (Sandbox Code Playgroud)
做这样的事情的最佳方法是什么?
当尝试使用任意参数集调用子类中的函数时,我遇到以下问题:
class Base{
function callDerived($method,$params){
call_user_func_array(array($this,$method),$params);
}
}
class Derived extends Base{
function test($foo,$bar){
print "foo=$foo, bar=$bar\n";
}
}
$d = new Derived();
$d->callDerived('test',array('bar'=>'2','foo'=>1));
Run Code Online (Sandbox Code Playgroud)
输出:
foo=2, bar=1
Run Code Online (Sandbox Code Playgroud)
哪个...并不是我想要的 - 除了使用func_get_args的索引顺序重新组合数组之外,有没有办法实现这一目标?是的,当然,我可以简单地传递整个数组并在函数中处理它...但这不是我想要做的.
谢谢
如何在 PHP 7+ 中实现命名参数功能?
理想的语法是:
find($wildcard, relative = true, listIfEmpty = false) {
...
}
Run Code Online (Sandbox Code Playgroud)
但是没有这样的解决方案。在答案中,我实现了最短的解决方案,支持:
有关更多信息和实施,请参阅答案