How would I skip optional arguments in a function call?

OK I totally forgot how to skip arguments in PHP.

Lets say I have:

function getData($name, $limit = '50', $page = '1') {
    ...
}

How would I call this function so that the middle parameter takes the default value (ie. '50')?

getData('some name', '', '23');

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


Solution 1:

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.

Solution 2:

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.

Solution 3:

Nope, it's not possible to skip arguments this way. You can omit passing arguments only if they are at the end of the parameter list.

There was an official proposal for this: https://wiki.php.net/rfc/skipparams, which got declined. The proposal page links to other SO questions on this topic.