Forum Moderators: coopster

Message Too Old, No Replies

how to use a default parameter that isn't last in parameter list?

         

pixeltierra

7:02 pm on Oct 3, 2008 (gmt 0)

10+ Year Member



I have

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.

eelixduppy

8:46 pm on Oct 3, 2008 (gmt 0)



Why not just call it with a 2? Works the same way.

foo('3', '2', '5');

nick279

9:28 pm on Oct 3, 2008 (gmt 0)

10+ Year Member



You could try:-

function foo($a,$b=false,$c)
{
$b = ($b) ? $b : 2;
}

then call it

foo(3,false,6);

pixeltierra

10:35 pm on Oct 3, 2008 (gmt 0)

10+ Year Member



nick: this seems like the only option. On a function. I'll probably just make a class instead. More code, but more flexible.

Still it seems like valuable functionality to have that is missing.

grallis

11:56 pm on Oct 3, 2008 (gmt 0)

10+ Year Member



Hi pixeltierra -

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

pinterface

1:18 am on Oct 4, 2008 (gmt 0)

10+ Year Member



Taking nick279's suggestion a little further, you might try:
define('_', null);
function foo($a = 1, $b = 2, $c = 3) {
$b = is_null($b) ? 2 : $b;
// do whatever...
}
foo(3, _, 5);
which gets you pretty close, and still allows $b to be false (if you need that).

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:

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...
}
You could then call it as:
foo(array('a' => '3', 'c' => '5')); // or
foo('6', '7', '8'); // or
foo(array('c' => 10, 'b' => 11));
which is pretty heavy syntactically, but gives you a lot of calling options.