@Chiang
2020-01-07T14:03:08.000000Z
字数 2343
阅读 530
PHP
- PHP 在用户自定义函数中支持可变数量的参数列表。在 PHP 5.6 及以上的版本中,由 ... 语法实现;在 PHP 5.5 及更早版本中,使用函数 func_num_args(),func_get_arg(),和 func_get_args() 。
- In PHP 5.6 and later, argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);//10
?>
- You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:
<?php
function add($a, $b) {
return $a + $b;
}
echo add(...[1, 2])."\n";//3
$a = [1, 2];
echo add(...$a);//3
?>
- You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....
- It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.
<?php
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
Finally, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).
Older versions of PHP
- No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().
- The first example above would be implemented as follows in PHP 5.5 and earlier:
<?php
function sum() {
$acc = 0;
foreach (func_get_args() as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);//10
?>
func_num_args — Returns the number of arguments passed to the function
func_num_args ( void ) : int
- Gets the number of arguments passed to the function.
- This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
func_get_arg — 返回参数列表的某一项
func_get_arg ( int $arg_num ) : mixed
- 从用户自定义函数的参数列表中获取某个指定的参数。
- 该函数可以配合 func_get_args() 和 func_num_args() 一起使用,从而使得用户自定义函数可以接受自定义个数的参数列表。
- 参数
arg_num
参数的偏移量。函数的参数是从0开始计数的。- 返回值
返回指定的参数,错误则返回 FALSE
func_get_args — 返回一个包含函数参数列表的数组
func_get_args ( void ) : array