PHP 支持按值传递参数(默认),通过引用传递参数以及默认参数。也支持可变长度参数列表。
引用传递
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
默认参数:
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
默认值必须是常量表达式,不能是诸如变量,类成员,或者函数调用等
Note: 自 PHP 5 起,传引用的参数也可以有默认值。
Type declarations
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.e.g.,
function f(C $c) {
echo get_class($c)."\n";
}
Strict typing
declare(strict_types=1);
try {
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
echo 'Error: '.$e->getMessage();
}
可变数量的参数列表
PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args()
New version:
<?phpfunction sum (... $numbers ) {
$acc = 0 ;
foreach ( $numbers as $n ) {
$acc += $n ;
}
return $acc ;
}
echo sum ( 1 , 2 , 3 , 4 );
?>
Old version:
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);