PHP中如何将数组作为参数,在PHP中将数组作为参数而不是数组传递

如前所述,从PHP 5.6+开始,您可以(应该!)使用...令牌(即splat运算符,可变参数函数功能的一部分)轻松地调用带有参数数组的函数:

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运算符参数,以确保所有传递的值都与特定类型匹配。

(请记住,这样做必须是您定义的最后一个参数,并将传递给函数的所有参数捆绑到数组中。)

确保数组包含特定类型的项目非常有用:

// 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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值