4

I have a piece of code let's say:

function nums($a = 1, $b = 2, $c){
    echo "$a, $b, $c";
}

nums(?, ?, 3);

Can I somehow substitute ? to tell PHP to use default values for those arguments, and only pass that one argument that is needed, or is it done only by placing $c first in the parameter list and then the optional parameters?

Arno
  • 356
  • 5
  • 18

1 Answers1

6

Put the default parameters at the end, then don't fill in the parameter in the function call.

example:

function nums($c, $a = 1, $b = 2){
    echo "$a, $b, $c";
}

nums(3);

Default parameters can be overridden by adding them to the function call:

function nums($c, $a = 1, $b = 2){
    echo "$a, $b, $c";
}

nums(3, 12, 27);
RattleyCooper
  • 4,997
  • 5
  • 27
  • 43
  • Just curious if it could be done that alternative way, since it could be possible that you have 1st parameter that needs specifying, and then you specify only the 3rd and want the 2nd parameter to use the default value instead. Thank you anyway – Arno Apr 02 '15 at 19:47
  • 1
    @Arno, Not that I'm aware of. Unless you know the default values and pass them in each time you call the function, but that would kind of defeat the purpose of having a default argument. – RattleyCooper Apr 02 '15 at 19:50