函数可以定义 C++ 风格的标量参数默认值,如下所示:
Example #3 在函数中使用默认参数
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.
";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
以上例程会输出:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
PHP 还允许使用数组 array 和特殊类型 NULL 作为默认参数,例如:
Example #4 使用非标量类型作为默认参数
<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.
";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>
默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等。
注意当使用默认参数时,任何默认参数必须放在任何非默认参数的右侧;否则,函数将不会按照预期的情况工作。考虑下面的代码片断:
Example #5 函数默认参数的不正确用法
<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.
";
}
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 .
现在,比较上面的例子和这个例子:
Example #6 函数默认参数正确的用法
<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.
";
}
echo makeyogurt("raspberry"); // works as expected
?>
以上例程会输出:
Making a bowl of acidophilus raspberry.
Note: 自 PHP 5 起,传引用的参数也可以有默认值。