Question

in many languages I can do something like this:

function f(a = 0, b = 0, c = 0)
{
   // Do something
}

f(b=3, c=4);

Can I do something like this in PHP?

Thank you very much indeed!

Était-ce utile?

La solution

No, unfortunately you can't "step over" arguments in PHP, so default values are only possible at the end of the list.

So you can write this:

 function foo($a=0, $b=0) {}
 foo(42);

Here $b will have its default value but $a won't, as we provided one value as input.

However there's no way of providing a value for $b without also providing one for $a - we have to provide the value for $b as the second parameter, and PHP has no keyword we can use in place of the first parameter to say "use default".

There is talk of adding named parameters to a future version of PHP, similar to your non-PHP example.

You can simulate this a bit with some changes to your code, though; a couple of ideas:

  • treat null as meaning "use default", and write $a = is_null($a) ? 42 : $a
  • make your functions take an associative array as their only parameter, and take values from it as though their keys were parameter names

Autres conseils

Indeed.

function foo($bar = "test") {
    echo "I want ".$bar;
}

In PHP this is not possible: see the PHP Manual. Function parameters are always evaluated from left to right.

However,

f($b=3, $c=4);

is possible, but does something different as you will expect: before the function f() is called, the arguments are evaluated (variable $b and $c get assigned with the values 3 and 4 resp.) and then the function is called as

f(3,4)

As side effect, the variables $b and $c are set to the new values.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top