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

时间:2009-04-13 14:55:15

标签: php arrays function methods

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

它可能就像func(&$myArgs)一样简单,但我很确定不是它。但是,遗憾的是,到目前为止,php.net手册尚未透露任何内容。并非我在过去一年左右不得不使用这一特定功能。

4 个答案:

答案 0 :(得分:162)

答案 1 :(得分:113)

As has been mentioned,从PHP 5.6+开始,您可以(应该!)使用...令牌(又名“splat operator”,variadic functions功能的一部分)来轻松调用函数带有一组参数:

<?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's comment,这种形式的参数解包是迄今为止最快的方法。在某些比较中,它比call_user_func_array快5倍。

除了

因为我认为这非常有用(虽然与问题没有直接关系):您可以在函数定义中type-hint the splat operator parameter来确保所有传递的值都与特定类型匹配。

(请记住,这样做必须是你定义的 last 参数,它将传递给函数的所有参数捆绑到数组中。)

这非常适合确保数组包含特定类型的项目:

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

答案 2 :(得分:81)

另请注意,如果要将实例方法应用于数组,则需要将函数传递为:

call_user_func_array(array($instance, "MethodName"), $myArgs);

答案 3 :(得分:10)

为了完整起见,从PHP 5.1开始,这也适用:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

请参阅:http://php.net/reflectionfunction.invokeargs

对于方法,您使用ReflectionMethod::invokeArgs代替并将对象作为第一个参数传递。