Default parameters

Asked

Viewed 1,659 times

5

I’m having a problem with the parameters in a PHP function.

For example:

function exemplo($par1 = 1, $par2 = 2) {
    return $par1 . " - " . $par2;
}

exemplo();        // 1 - 2
exemplo(3);       // 3 - 2
exemplo(3, 4);    // 3 - 4
exemplo(null, 4); //   - 4

On the last call, I’m trying to pass just the according to parameter and keep the first as default, but that’s not what happens (the variable gets value null).

It is possible to achieve the desired behavior in this case?

5 answers

5

There is no way to 'skip' the first parameter, but what you can do is a condition for the null be worked with the parameter.

function exemplo( $par1 = 1 , $par2 = 2 )
{
    return ( ! isset( $par1 ) ? 1 : $par1 ) . " - " . $par2;
}

exemplo( null , 4 );

output : 1 - 4

I updated the response to use ternary operator on a line.

3

PHP does not yet have named parameters, as there is in the Python, therefore, what can be done (in addition to the alternatives already mentioned) is to pass a array as a parameter for the function.

But there are certain disadvantages, as the available parameters are not documented in signing, it is necessary to look in the function code to discover, another drawback is that it requires more code to implement, because the standards values must be mixed with the values indicated in the function call.

Initial implementation of named parameters can be seen here.

Example:

function exemplo(array $args) {
    $pares = array('par1' => 1, 'par2' => 2);
    $args = array_merge($pares, array_intersect_key($args, $pares));
    list($par1, $par2) = array_values($args);
    
    return $par1 .' - '. $par2;
}

Utilizing:

echo exemplo([]) . "\n";                         // 1 - 2
echo exemplo(['par1' => 3]) . "\n";              // 3 - 2
echo exemplo(['par1' => 3, 'par2' => 4]) . "\n"; // 3 - 4
echo exemplo(['par2' => 4]) . "\n";              // 1 - 4

DEMO

  • For less gambit, http://php.net/manual/en/functions.arguments.php#functions.variable-Arg-list

  • 2

    @I don’t think it’s funny, because the php page that I mentioned, future intends to adopt a syntax similar to this, see the section Open questions, and see also the section func_* and call_user_func_array.

  • 1

    I understood your point, I think you could quote the named params more clearly in your answer, rather than using "this feature".

2

The best way to treat this type of situation is to use the function func_get_args(). The use is simple: You declare the function without any parameter and within the function use the func_get_args() to collect the parameters passed. An example would be:

function exemplo() {
   $parametros = func_get_args();
   if(!empty($parametros)) {
       $parametro1 = $parametros[0];
       $parametro2 = $parametros[1];
       ...
       $parametroN = $parametros[N];
   }
}

exemplo();
exemplo('arg1', 'arg2');
exemplo('arg1', 'arg2', ..., 'argn');
  • See what’s new in PHP, there’s a more modern way to do this. http://php.net/manual/en/functions.arguments.php#functions.variable-Arg-list

2

function exemplo($par1 = null, $par2 = null) {
    $_par1 = null === $par1 ? 1 : $par1;
    $_par2 = null === $par2 ? 2 : $par2;
    return $_par1 . ' - ' . $_par2;
}

Consistent behavior if you use exemplo(null, null)

  • 1

    If the pattern is $par1 = null, $par2 = null, why spend exemplo(null, null)? Suffice exemplo() or take the default from the function exemplo($par1 , $par2 )

  • if the second parameter is the result of a function, this behavior is useful, as this result may be null.

  • I didn’t mean it... Your answer is correct and more complete than mine by the way, the OBS I made was that the call exemplo() already makes use of the default values sme need to pass NULL , NULL.

  • In the comment I answered your question: "why pass example(null, null)?".

1

Look, I’m not saying it’s the right one, but whenever I need to use parameters with values default, I try to leave them last in the function, as follows:

function exemplo ($arg1, $arg2 = null) {
    // Corpo da função
}

This way it is easy to control, mandatory parameters must be passed first, since those that have values default, lastly.

The calls to the function would look like this:

exemplo($arg1);
exemplo($arg1, $arg2);

There is a new way to do what has been proposed, but as a requirement, you must have installed the PHP 5.6 or higher, that would be:

function somar (...$numeros) {
    $soma = 0;
    foreach ($numeros as $numero) {
        $soma += $numero;
    }
    return $soma;
}

...$numbers - Indicates that the function will have a variable number of parameters, and these will be stored in that variable of type Array

The calls to the function would look like this:

somar(1, 3, 5);
somar(5, 7, 18, 20, 63, 72, 12, 54);
  • I always leave the options last. As for the parameters using ... use only func_get_args...

Browser other questions tagged

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