php 关于函数参数的默认值

在写函数的时,有时我们会给参数设置默认值,如果参数默认值没有书写正确会引起警告,因此在这里整理一下正确使用方式

1.默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等。

2.注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧;否则,函数将不会按照预期的情况工作。除非在调用的时候按照参数顺序都书写上,比较下面两个片段

function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected

以上代码会输出

Warning: Missing argument 2 in call to makeyogurt() in 
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Making a bowl of raspberry .

但是如果是按照

function pin( $c=0,$b) {
   $c++;
   if( $c <= $b  ) {
     return $c . '/'.pin( $c,$b );

   }
}
$a = pin(0,10);
echo $a;

这样对应的顺序去写,没有问题,只是默认值的作用就没有了,而且第一个参数必须要有,否则报错
因此,最好的方法是默认参数必须放在任何非默认参数的右侧

function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // works as expected

以上代码会输出

Making a bowl of acidophilus raspberry.
posted @ 2018-12-21 10:58  MrBear  阅读(9918)  评论(0编辑  收藏  举报