简体   繁体   English

PHP-参数默认值

[英]PHP - Parameters default values

I have a function with multiple parameters. 我有一个带有多个参数的函数。 Sometimes the user may need to specify, say, the first, second, and fourth, but not the third. 有时,用户可能需要指定例如第一,第二和第四,而不是第三。 In JavaScript we can do that easily using an anonymous object as a single parameter for the whole function : 在JavaScript中,我们可以轻松地使用匿名对象作为整个函数的单个参数来做到这一点:

function foo(args) {
    if(args.arg0 != null) alert(args.arg0);
    if(args.arg1 != null) alert(args.arg2);
    if(args.arg2 != null) alert(args.arg1);
}

foo({
   arg0: 'foo',
   arg2: 10
});

If i want to do that in PHP, i can use an associative array to play the same role as this anonymous objects "args" in the function above : 如果我想在PHP中做到这一点,我可以使用关联数组来扮演与上述函数中的匿名对象“ args”相同的角色:

foo(array(
   'arg0' => 'foo',
   'arg2' => 10
));

Which would not be possible using multiple parameters as one may not write : 使用多个参数不可能做到这一点,因为它可能不会写:

foo('foo', , 10);

For some reason i find using arrays dirty for that, and wonder if there isn't a "cleaner" way. 由于某种原因,我发现为此使用了肮脏的数组,并且想知道是否没有“更清洁”的方式。

Thanks for your help :) 谢谢你的帮助 :)

I agree with other commenters that say an array is a good solution. 我同意其他评论者的观点,他们说数组是一个很好的解决方案。 However, if you still want a different way to handle this check func_get_args() 但是,如果您仍然希望以其他方式来处理此检查,那么func_get_args()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM