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.
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.
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.
Nothing has changed regarding being able to skip optional arguments, however for correct syntax and to be able to specify NULL for arguments that I want to skip, here's how I'd do it:
define('DEFAULT_DATA_LIMIT', '50');
define('DEFAULT_DATA_PAGE', '1');
/**
* getData
* get a page of data
*
* Parameters:
* name - (required) the name of data to obtain
* limit - (optional) send NULL to get the default limit: 50
* page - (optional) send NULL to get the default page: 1
* Returns:
* a page of data as an array
*/
function getData($name, $limit = NULL, $page = NULL) {
$limit = ($limit===NULL) ? DEFAULT_DATA_LIMIT : $limit;
$page = ($page===NULL) ? DEFAULT_DATA_PAGE : $page;
...
}
This can the be called thusly: getData('some name',NULL,'23');
and anyone calling the function in future need not remember the defaults every time or the constant declared for them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With