noh*_*hat 111 php variadic-functions
我有一个PHP函数,它接受可变数量的参数(使用func_num_args()和func_get_args()),但我想传递函数的参数数量取决于数组的长度.有没有办法用可变数量的参数调用 PHP函数?
Pas*_*TIN 127
如果您在数组中有自己的参数,那么您可能会对该call_user_func_array函数感兴趣.
如果要传递的参数数量取决于数组的长度,则可能意味着您可以将它们自己打包到数组中 - 并将其用于第二个参数call_user_func_array.
然后,您传递的数组元素将作为不同的参数接收.
例如,如果你有这个功能:
function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}
Run Code Online (Sandbox Code Playgroud)
您可以将参数打包到数组中,如下所示:
$params = array(
10,
'glop',
'test',
);
Run Code Online (Sandbox Code Playgroud)
然后,调用函数:
call_user_func_array('test', $params);
Run Code Online (Sandbox Code Playgroud)
这段代码将输出:
int 3
array
0 => int 10
1 => string 'glop' (length=4)
2 => string 'test' (length=4)
Run Code Online (Sandbox Code Playgroud)
即3个参数; 完全像iof函数这样调用:
test(10, 'glop', 'test');
Run Code Online (Sandbox Code Playgroud)
JCM*_*JCM 56
现在可以使用PHP 5.6.x,使用...运算符(在某些语言中也称为splat运算符):
例:
function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
foreach ( $intervals as $interval ) {
$dt->add( $interval );
}
return $dt;
}
addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ),
new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );
Run Code Online (Sandbox Code Playgroud)
Sal*_*ali 44
在新的Php 5.6中,您可以使用... operator而不是使用func_get_args().
因此,使用此功能,您可以获得所有传递的参数:
function manyVars(...$params) {
var_dump($params);
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ndo 36
从PHP 5.6开始,可以使用...运算符指定变量参数列表.
function do_something($first, ...$all_the_others)
{
var_dump($first);
var_dump($all_the_others);
}
do_something('this goes in first', 2, 3, 4, 5);
#> string(18) "this goes in first"
#>
#> array(4) {
#> [0]=>
#> int(2)
#> [1]=>
#> int(3)
#> [2]=>
#> int(4)
#> [3]=>
#> int(5)
#> }
Run Code Online (Sandbox Code Playgroud)
如您所见,...运算符收集数组中的变量参数列表.
如果您需要将变量参数传递给另一个函数,...它仍然可以帮助您.
function do_something($first, ...$all_the_others)
{
do_something_else($first, ...$all_the_others);
// Which is translated to:
// do_something_else('this goes in first', 2, 3, 4, 5);
}
Run Code Online (Sandbox Code Playgroud)
从PHP 7开始,变量参数列表也可以强制为所有相同的类型.
function do_something($first, int ...$all_the_others) { /**/ }
Run Code Online (Sandbox Code Playgroud)
小智 10
对于那些寻找方法的人$object->method:
call_user_func_array(array($object, 'method_name'), $array);
Run Code Online (Sandbox Code Playgroud)
我在一个构造函数中成功地使用它来调用带有可变参数的变量method_name.
你可以直接调用它。
function test(){
print_r(func_get_args());
}
test("blah");
test("blah","blah");
Run Code Online (Sandbox Code Playgroud)
输出:
数组 ( [0] => 等等 ) 数组 ( [0] => 等等 [1] => 等等 )