简体   繁体   English

PHP默认参数值:编译器如何知道哪个参数传递的参数值?

[英]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 )? 在以下代码段中, printPhrase如何知道传递的参数是$a$b (因此使用默认值$c还是$a$c (因此使用默认值$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. 在php中,参数总是从左到右传递而不会跳过。 So printPhrase('A ', ' cat!'); 所以printPhrase('A ', ' cat!'); always fills with values first and second argument of function. 总是用函数的第一个和第二个参数填充值。

http://php.net/manual/en/functions.arguments.php#functions.arguments.default http://php.net/manual/zh-CN/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 如果要使用默认参数,则需要像以下答案中那样重写代码: 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. 由于您已经传递了2个参数,它们将被视为$ a和$ b的参数。 So it will possible print something like A cat candle! 这样就可以打印类似A cat candle!东西了A cat candle! You need to pass null value in the second argument if it is to take the value of $b ie 如果要采用$ b的值,则需要在第二个参数中传递null值,即

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

This will give you an output A black cat! 这将为您提供输出A黑猫!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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