Function with variable length argument list
If I have the following function:
function foo($a = 'a', $b = 'b', $c = 'c', $d = 'd')
{
// Do something
}
Can I call this function and only pass the value for $d, therefore leaving all the other arguments with their defaults? With code something like this:
foo('bar');
Or do I have to call i开发者_高级运维t with something like this:
foo(null, null, null, 'bar');
No, you cannot. Use arrays:
function foo($args) {
extract($args);
echo $bar + $baz;
}
foo(array("bar" => 123, "baz" => 456));
Write a bug report on php.net and ask them to add named arguments to the language!
You have to use nulls like you said:
foo(null, null, null, 'bar');
If you don't mind creating more functions you could do something like this, I'd imagine the overall code would be neater.
function update_d($val){
foo(null, null, null, $val);
}
Or you could use arrays like so:
$args = array($a = 'a', $b = 'b', $c = 'c', $d = 'd');
foo($args);
You have to do it like
foo(null, null, null, 'bar');
An alternative is to leave the arguments out of the function signature, and use func_get_args()
to retrieve the values;
function foo() {
$args = func_get_args();
But then still, if you would leave out the first three null
values, there's no way to know that 'bar' is the $d
parameter. Note by the way that this approach is undesirable most of the times, because it obfuscates your function signature and hurts performance.
Short answer: No. Long answer: Nooooooooooooooooooooooooooooo.
Default argument value will be used when the variable is not set at all.
You can't do it without overloading techniques.
In this case, your program assumes that if only one param is passed, it's the fourth.
func_get_args() - Gets an array of the function's argument list.
func_num_args() - Returns the number of arguments passed to the function
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
}
foo(a); foo(1,b,c); will work fine
精彩评论