ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
[PHP: 函数 - Manual](https://www.php.net/manual/zh/language.functions.php) ### 可变数量的参数列表 PHP 在用户自定义函数中支持可变数量的参数列表。由`...`语法实现。 > **注意**:还可以使用以下函数来获取可变参数[func\_num\_args()](https://www.php.net/manual/zh/function.func-num-args.php)、[func\_get\_arg()](https://www.php.net/manual/zh/function.func-get-arg.php)和[func\_get\_args()](https://www.php.net/manual/zh/function.func-get-args.php),不建议使用此方式,请使用`...`来替代。 包含`...`的参数,会转换为指定参数变量的一个数组,见以下示例: **示例 #9 使用`...`来访问变量参数** ``` function sum(...$numbers) {     $acc = 0;     foreach ($numbers as $n) {         $acc += $n;     }     return $acc; } echo sum(1, 2, 3, 4); ``` 以上例程会输出: ~~~ 10 ~~~ 也可以使用`...`语法来传递array或**Traversable**做为参数到函数中: **示例 #10 使用`...`来传递参数** ``` function add($a, $b) {     return $a + $b; } echo add(...[1, 2])."\n"; $a = [1, 2]; echo add(...$a); ``` 以上例程会输出: ~~~ 3 3 ~~~ 你可以在`...`前指定正常的位置参数。在这种情况下,只有不符合位置参数的尾部参数才会被添加到`...`生成的数组中。 你也可以在`...`标记前添加一个[类型声明](https://www.php.net/manual/zh/language.types.declarations.php)。如果存在这种情况,那么`...`捕获的所有参数必须是提示类的对象。 **示例 #11 输入提示的变量参数** ``` function total_intervals($unit, DateInterval ...$intervals) {     $time = 0;     foreach ($intervals as $interval) {         $time += $interval->$unit;     }     return $time; } $a = new DateInterval('P1D'); $b = new DateInterval('P2D'); echo total_intervals('d', $a, $b).' days'; // This will fail, since null isn't a DateInterval object. echo total_intervals('d', null); ``` 以上例程会输出: ~~~ 3 days Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2 ~~~ #### 旧版本的 PHP 不需要特殊的语法来声明一个函数是可变的;但是访问函数的参数必须使用[func\_num\_args()](https://www.php.net/manual/zh/function.func-num-args.php),[func\_get\_arg()](https://www.php.net/manual/zh/function.func-get-arg.php)和[func\_get\_args()](https://www.php.net/manual/zh/function.func-get-args.php)函数。 上面的第一个例子在早期 PHP 版本中的实现如下: **示例 #12 在 PHP 早期版本中访问可变参数** `<?php function sum() {     $acc = 0;     foreach (func_get_args() as $n) {         $acc += $n;     }     return $acc; } echo sum(1, 2, 3, 4); ?>` 以上例程会输出: ~~~ 10 ~~~ ### **命名参数** 命名参数通过在参数名前加上冒号来传递。允许使用保留关键字作为参数名。参数名必须是一个标识符,不允许动态指定 格式:(定义时的参数名或者参数类型(不接受变量): 参数的值(可接受变量)) array_fill定义:**array_fill**(int `$start_index`,int `$count`,mixed `$value`): ``` //通常传递参数 array_fill(0, 100, 50); //使用命名参数(好处就是参数的顺序不在重要) array_fill(start_index: 0, count: 100, value: 50); array_fill(value: 50, count: 100, start_index: 0); ```