Forum Moderators: coopster
function foo ($a='1', $b='2', $c='3') {
}
and want to call it like this
foo ('3', default, '5');
Where default above is what is the default in the function definition. Is this possible? I know that this is easy if the parameter(s) is the last in the list, just don't include it.
Thanks in advance.
foo('3', '2', '5');
I personally use nick's way when possible. I'm not sure if this will help you, but there is a way to pass how ever many variables you'd like into the function and have the function accept the parameters.
With the use of:
func_get_arg();
func_get_args();
func_num_args();
... you can count, collect and use all the variables passed into your function.
func_num_args() counts the number of arguments passed into the function.
func_get_args() can be used to assign the arguments to another array like so: $args = func_get_args();
func_get_arg() is used to access one argument. $arg = func_get_arg(2);
Not sure if that helps ... could just be another heap of useless information in my head :P
which gets you pretty close, and still allows $b to be false (if you need that).define('_', null);
function foo($a = 1, $b = 2, $c = 3) {
$b = is_null($b) ? 2 : $b;
// do whatever...
}
foo(3, _, 5);
But in terms of actually being supported by PHP, no, it isn't. The only language I can think of where you can do what you want is Visual Basic (
foo '3', , '5'). The usual solution to having multiple optional parameters which may be specified in any order is named parameters, but PHP doesn't support them. You could, however, fake them.
Suppose foo looked more like:
You could then call it as:function foo ($a='1', $b='2', $c='3') {
if (func_num_args() === 1 && is_array($a)) {
foreach (array('c', 'b') as $k)
$$k = array_key_exists($k, $a) ? $a[$k] : $$k;
$a = array_key_exists('a', $a) ? $a['a'] : '1';
}
// do whatever...
}
which is pretty heavy syntactically, but gives you a lot of calling options.foo(array('a' => '3', 'c' => '5')); // or
foo('6', '7', '8'); // or
foo(array('c' => 10, 'b' => 11));