Any way to specify optional parameter values in PHP?
PHP does not support named parameters for functions per se. However, there are some ways to get around this:
- Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array.
- If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do.
- Pass a null value to any argument you don't want to specify. Not really getting around it, but it works.
- If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed.
A variation on the array technique that allows for easier setting of default values:
function foo($arguments) { $defaults = array( 'firstName' => 'john', 'lastName' => 'doe', ); $arguments = array_merge($defaults, $arguments); echo $arguments['firstName'] . ' ' . $arguments['lastName'];}
Usage:
foo(array('lastName' => 'smith')); // output: john smith
You could refactor your code slightly:
function foo($firstName = NULL, $lastName = NULL){ if (is_null($firstName)) { $firstName = 'john'; } if (is_null($lastName )) { $lastName = 'doe'; } echo $firstName . " " . $lastName;}foo(); // john doefoo('bill'); // bill doefoo(NULL,'smith'); // john smithfoo('bill','smith'); // bill smith