It has many ways, depends on the desired effect.
The normal is you for always the options on the right, precisely to be able to omit:
function foo($requerido, $opcional = 12)
{
...
}
But if standard behavior doesn’t fit, you can do something like this:
function foo($opcional1, $opcional2 = 12)
{
if ($opcional1 === null) $opcional1 = 25;
}
Or even, in PHP 7+:
function foo($opcional1, $opcional2 = 12)
{
$opcional1 = $opcional1 ?? 25;
}
Then you pass a null when calling, to use the value default:
foo( null, 27 );
(or another "magical" value that you choose as default)
Note that this construction also serves to solve another problem, which is the need for nonconstant values (imagine if the default for time()
, for example - in this case it cannot be assigned to function
anyway, for not being constant)
Variadic functions
Another way is to use the variadic functions, introduced in PHP5.6:
function minhavariadica(...$argumentos) {
if( count( $argumentos ) == 2 ) {
$opcional1 = $argumentos[0];
$opcional2 = $argumentos[1];
} else {
$opcional2 = $argumentos[0];
}
}
Associative or object array
If you really have a very variable number of parameters, maybe it’s best to use a structure, avoiding the positional parameters completely:
$estrutura['nome'] = 'José';
$estrutura['idade'] = 12;
$estrutura['sangue'] = TYPE_O_POSITIVE;
processadados($estrutura);
function processadados($e) {
$nome = isset($e['nome']?$e['nome']:'desconhecido'; // $e['nome']??'desconhecido' PHP7+
$idade = ...
... mesma coisa para cada dado, ou usa literalmente no código...
The advantage in this case is that things already enter the function with their proper name in the index, making the "conversion" into new variable an optional step.