php – How can I set a value to a specific variable in a function with optional attributes?

Question:

I made the following code to illustrate my problem:

function teste($valor1 = '', $valor2 = ''){
    echo "Valor1: " . $valor1;
    echo "</br>";
    echo "Valor2: " . $valor2;  
}

A very simple function, if I do this:

teste('aqui', 'aqui tambem');

The result will be:

Valor1: aqui Valor2: aqui tambem

So far so good, but what I need is to send the value only to the second attribute, I tried as follows:

teste($valor2 = 'Aqui');

But the result was this:

Valor1: Aqui Valor2:

Using python for example I can define which attribute the value will be set in this way, putting the variable name and assigning the value to the function, but in php it doesn't work that way.

How can I set a value to a specific variable in a function with optional attributes?

Answer:

There are many ways, it depends on the desired effect.

Normally, you always put the options on the right, just to be able to omit:

function foo($requerido, $opcional = 12)
{
   ...
}

But if the default behavior doesn't 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 you choose as default )

Note that this construction also serves to solve another problem, which is the need for non-constant values ​​(imagine if the default is time() , for example – in this case it cannot be assigned in the function anyway, as it is not 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 array or object

If you really have a very variable number of parameters, maybe it's best to use a structure, avoiding positional parameters altogether:

$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 its proper name in the index, making "conversion" to a new variable an optional step.

Scroll to Top