0

The issue is, I have a function with 3 parameters. All three parameters have a default value. But is it possible to call the function with only one of the parameters like so:

function check($a=1, $b=2, $c=3){
   echo 'a : ' . $a;
   echo 'b : ' . $b;
   echo 'c : ' . $c;
}

$res = check($c=5);

And expect the following result:

a : 1
b : 2
c : 5

I have tried using this kind of code but what happens is that $c=5 is passed to the first parameter. In this case to $a

  • Or https://stackoverflow.com/questions/1342908/named-php-optional-arguments – misorude Oct 22 '18 at 11:18
  • @FrenchCliffordDacion. With the look of things, the result should be 5,2,3. Since for the first argument you passed the value is taken and not the variable declaration. I suppose the explanation to this is scope. Isn't it that `check($c=5);` creates a new variable c and initialises it outside the function? – Oluwatobi Samuel Omisakin Oct 22 '18 at 11:21
  • Not yet, but it's been proposed for future versions of PHP https://wiki.php.net/rfc/named_params I try to keep aprised of all the new things.... – ArtisticPhoenix Oct 22 '18 at 11:26
  • Thanks for all the answers and comments. :D It really helped me a lot! :D – French Clifford Dacion Oct 23 '18 at 02:12

1 Answers1

3

No you can't do that in this way. PHP excpects the values in the order you defined in the function. However it is possible to pass data to your function as an array.

$res = check(array('a' => $defaulta, ..., 'c' => 5))

Where you have your default values in somethin like $defaulta/b/c. Or just write them hardcoded.

Hope this helps!

errorinpersona
  • 380
  • 5
  • 17