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

我似乎记得在PHP中,有一种方法可以将数组作为函数的参数列表传递,以标准func($arg1, $arg2)方式取消对数组的引用。但是现在我迷失了如何做。我记得通过引用传递的方式,如何“遍历”传入的参数……但没有如何将数组从列表中除名。

它可能和一样简单func(&$myArgs),但是我敢肯定不是。但是,可悲的是,到目前为止,php.net手册还没有透露任何内容。并不是说我在过去一年左右的时间里不得不使用此特定功能。


喵喔喔
浏览 792回答 3
3回答

慕桂英546537

如前所述,从PHP 5.6+开始,您可以(应该!)使用...令牌(即splat运算符,可变参数函数功能的一部分)轻松地调用带有参数数组的函数:<?phpfunction variadic($arg1, $arg2){&nbsp; &nbsp; // Do stuff&nbsp; &nbsp; echo $arg1.' '.$arg2;}$array = ['Hello', 'World'];// 'Splat' the $array in the function callvariadic(...$array);// 'Hello World'注意:数组项是根据其 在数组中的位置 而不是其键映射到参数的。根据CarlosCarucce的评论,这种形式的参数解压缩是迄今为止所有情况下最快的方法。在某些比较中,速度比快5倍以上call_user_func_array。在旁边因为我认为这确实有用(尽管与问题没有直接关系):您可以在函数定义中键入splat运算符参数,以确保所有传递的值都与特定类型匹配。(请记住,这样做必须是您定义的最后一个参数,并将传递给函数的所有参数捆绑到数组中。)确保数组包含特定类型的项目非常有用:<?php// Define the function...function variadic($var, SomeClass ...$items){&nbsp; &nbsp; // $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 = [&nbsp; &nbsp; new SomeClass,&nbsp; &nbsp; new SomeClass,];variadic('Hello', ...$items);
打开App,查看更多内容
随时随地看视频慕课网APP