PHP Default parameter values: How does the compiler know which passed parameter-value is for which parameter?

49 views Asked by At

In the following snippet, how does printPhrase know if the passed arguments are $a and $b (so it uses default value of $c, or $a and $c (so it uses default value of $b)?

private function printPhrase ($a, $b='black', $c='candle!' ) {
  echo $a . $b . $c; //Prints A black cat! or A black candle!
}

private function callprintPhrase () {
  printPhrase('A ', ' cat!');
}
2

There are 2 answers

0
sectus On BEST ANSWER

In php arguments always passes from left to right with out skip. So printPhrase('A ', ' cat!'); always fills with values first and second argument of function.

http://php.net/manual/en/functions.arguments.php#functions.arguments.default

There is exists proposal to skip params.

If you want to use default params you need to rewrite your code like in this answer: https://stackoverflow.com/a/9541822/1503018

5
Aditya On
private function callprintPhrase () {
  printPhrase('A ', ' cat!');
}

since you have passed 2 arguments they will be considered as arguments for $a and $b. So it will possible print something like A cat candle! You need to pass null value in the second argument if it is to take the value of $b i.e.

private function callprintPhrase () {
      printPhrase('A ','', ' cat!');
    }

This will give you an output A black cat!