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

Asked

Viewed 52 times

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 as follows:

teste($valor2 = 'Aqui');

But the result was this:

Valor1: Aqui
Valor2:

Using python for example I can define in which attribute the value will be set this way, putting the variable name 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?

1 answer

8


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.