杉哥的个人博客

php 函数使用可变数量的参数

在php5.6以上版本可以使用…语法实现:

参数列表可以包含 标记,表示该函数接受可变数量的参数。参数将作为数组传递给给定变量。

例子1:使用…访问可变参数

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
//会输出:10
<?php function sum(...$numbers) { $acc = 0; foreach ($numbers as $n) { $acc += $n; } return $acc; } echo sum(1, 2, 3, 4); //会输出:10
<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
//会输出:10

例子2:数组转为参数列表

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
function add($a, $b){
echo $a + $b;
}
$args = array(1, 2);
add(...$args);
// 输出3
<?php function add($a, $b){ echo $a + $b; } $args = array(1, 2); add(...$args); // 输出3
<?php

function add($a, $b){
    echo $a + $b;
}

$args = array(1, 2);

add(...$args); 
// 输出3

例子3: 部分参数指定,其他参数数量不定

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
unction concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}
echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
unction concatenate($transform, ...$strings) { $string = ''; foreach($strings as $piece) { $string .= $piece; } return($transform($string)); } echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
unction concatenate($transform, ...$strings) {
  $string = '';
  foreach($strings as $piece) {
    $string .= $piece;
  }
  return($transform($string));
}

echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");