简体   繁体   中英

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

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!');
}

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

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 ie

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

This will give you an output A black cat!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM