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

5

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 the following way:

teste($valor2 = 'Aqui');

But the result was this:

Valor1: Aqui
Valor2:

Using python for example I can set in which attribute the value will be set this way, putting the name of the variable and assigning the value in the function, but in php it does not work this way.

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

    
asked by anonymous 05.03.2018 / 15:47

1 answer

8

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.

    
05.03.2018 / 16:01