3 回答
![?](http://img1.sycdn.imooc.com/5458502c00012d4a02200220-100-100.jpg)
TA贡献1848条经验 获得超10个赞
如前所述,从PHP 5.6+开始,您可以(应该!)使用...令牌(即splat运算符,可变参数函数功能的一部分)轻松地调用带有参数数组的函数:
<?php
function variadic($arg1, $arg2)
{
// Do stuff
echo $arg1.' '.$arg2;
}
$array = ['Hello', 'World'];
// 'Splat' the $array in the function call
variadic(...$array);
// 'Hello World'
注意:数组项是根据其 在数组中的位置 而不是其键映射到参数的。
根据CarlosCarucce的评论,这种形式的参数解压缩是迄今为止所有情况下最快的方法。在某些比较中,速度比快5倍以上call_user_func_array。
在旁边
因为我认为这确实有用(尽管与问题没有直接关系):您可以在函数定义中键入splat运算符参数,以确保所有传递的值都与特定类型匹配。
(请记住,这样做必须是您定义的最后一个参数,并将传递给函数的所有参数捆绑到数组中。)
确保数组包含特定类型的项目非常有用:
<?php
// Define the function...
function variadic($var, SomeClass ...$items)
{
// $items will be an array of objects of type `SomeClass`
}
// Then you can call...
variadic('Hello', new SomeClass, new SomeClass);
// or even splat both ways
$items = [
new SomeClass,
new SomeClass,
];
variadic('Hello', ...$items);
- 3 回答
- 0 关注
- 791 浏览
添加回答
举报