views:

695

answers:

3

OK I totally forgot how to skip arguments in PHP.

Lets say I have:

checkbox_field      
( 
$name,
$value = '',
$checked = false,
$compare = '',
$parameter = ''
)

How would I call this function and skip the second last argument?

checkbox_field('some name', 'some value', FALSE, '' , 'some parameter');

Would the above be correct? I can't seem to get this to work.

Thanks

+10  A: 

Your post is correct.

Unfortunately, if you need to use an optional parameter at the very end of the parameter list, you have to specify everything up until that last parameter. Generally if you want to mix-and-match, you give them default values of '' or null, and don't use them inside the function if they are that default value.

zombat
+8  A: 

There's no way to "skip" an argument other than to specify a default like false or null.

Since PHP lacks some syntactic sugar when it comes to this, you will often see something like this:

checkbox_field(array(
    'name' => 'some name',
    ....
));

Which, as eloquently said in the comments, is using arrays to emulate named arguments.

This gives ultimate flexibility but may not be needed in some cases. At the very least you can move whatever you think is not expected most of the time to the end of the argument list.

Paolo Bergantino
I would identify the 'something like this' as 'using arrays to emulate named arguments', FWIW. :)
chaos
Blerg. Fine. ;)
Paolo Bergantino
Despite being more flexible you have to remember the parameters you should/can set (as they are not in the signature). So in the end it might be not as useful as it seems but of course this depends on the context.
Felix Kling
A: 

There is a way, albeit with some "elegant" hackery. See:

http://www.seoegghead.com/software/php-parameter-skipping-and-named-parameters.seo

Jaimie Sirovich