There are many ways, depending on the effect you want.
The normal is you for always the options to the right, just to be able to omit:
function foo($requerido, $opcional = 12)
{
...
}
But if the default behavior does not work, 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 default value:
foo( null, 27 );
(or other "magic" value that you elect as default )
Note that this construct also serves to solve another problem, which is the need for non-constant values (imagine if default is time()
, for example - in this case it can not be assigned in function
anyway, not being constant)
Variable functions
Another way is to use the variable functions introduced in PHP5.6:
function minhavariadica(...$argumentos) {
if( count( $argumentos ) == 2 ) {
$opcional1 = $argumentos[0];
$opcional2 = $argumentos[1];
} else {
$opcional2 = $argumentos[0];
}
}
Associative Array or Object
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 here is that things already get into the function with their proper name in the index, making the "conversion" into new variable an optional step.