0

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!');
}
Solace
  • 8,612
  • 22
  • 95
  • 183

2 Answers2

2

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

Community
  • 1
  • 1
sectus
  • 15,605
  • 5
  • 55
  • 97
0
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!

Aditya
  • 1,241
  • 5
  • 19
  • 29
  • Just to be sure, do default arguments *also replace* the `null` or empty string values explicitly passed? – Solace Nov 26 '14 at 04:02
  • 1
    yes they do. empty strings get replaced and the same applies even if you explicitly pass **null** – Aditya Nov 26 '14 at 04:07
  • 2
    *This will give you an output A black cat!* -- will not. – sectus Nov 26 '14 at 04:11
  • @sectus Why not, when we are saying `''` gets replaced by the default value? – Solace Nov 26 '14 at 04:21
  • 1
    @Zarah, default value cannot replace any value: `15`, `null`, `stdClass` or whatever. If you have passed value this value would be passed to function body. – sectus Nov 26 '14 at 04:31