2010-01-22 125 views
10

有没有办法在PHP中定义一个函数,让你定义一个可变数量的参数?PHP:定义具有可变参数数量的函数?

在我比较熟悉它的语言,像这样:

function myFunction(...rest){ /* rest == array of params */ return rest.length; } 

myFunction("foo","bar"); // returns 2; 

谢谢!

回答

32

是的。使用func_num_args()func_get_arg()得到的参数:

<?php 
    function dynamic_args() { 
     echo "Number of arguments: " . func_num_args() . "<br />"; 
     for($i = 0 ; $i < func_num_args(); $i++) { 
      echo "Argument $i = " . func_get_arg($i) . "<br />"; 
     } 
    } 

    dynamic_args("a", "b", "c", "d", "e"); 
?> 

在PHP 5.6+您现在可以使用variadic functions

<?php 
    function dynamic_args(...$args) { 
     echo "Number of arguments: " . count($args) . "<br />"; 
     foreach ($args as $arg) { 
      echo $arg . "<br />"; 
     } 
    } 

    dynamic_args("a", "b", "c", "d", "e"); 
?> 
+2

很肯定'func_get_args( )'是你实际想要使用的而不是这个详细的第一个解决方案。 – Toskan 2014-06-17 05:14:11

0

我会鼓励你的数组传递给你的函数,这样你可以有存储在该阵列中的许多不同的参数。一旦数组在函数中获得所需的正确信息,就可以在数组上进行许多操作。

$array = array(); 
$array[0] = "a"; 
$array[1] = 1; 

myFunction($array); 
6

您可以接受可变数量的参数的任何功能,只要有足够的填充所有声明的参数。

<?php 

function test ($a, $b) { } 

test(3); // error 
test(4, 5); // ok 
test(6,7,8,9) // ok 

?> 

来访问传递给test()额外的未命名的参数,你可以使用函数func_get_args()func_num_args()func_get_arg($i)

<?php 

// Requires at least one param, $arg1 
function test($arg1) { 

    // func_get_args() returns all arguments passed, in order. 
    $args = func_get_args(); 

    // func_num_args() returns the number of arguments 
    assert(count($args) == func_num_args()); 

    // func_get_arg($n) returns the n'th argument, and the arguments returned by 
    // these functions always include those named explicitly, $arg1 in this case 
    assert(func_get_arg(0) == $arg1); 

    echo func_num_args(), "\n"; 
    echo implode(" & ", $args), "\n"; 

} 

test(1,2,3); // echo "1 & 2 & 3" 

?> 
1

我喜欢采用JavaScript式的方式与我的PHP参数。这可以更好地设置“选项”和它们的默认值(我会马上看看)。例如,假设你有一个函数返回一个数组的时间范围。参数1是开始时间,参数2是结束时间,参数3是时间间隔,之后的任何选项都是可选的(如“format”=>“24小时”,“include_seconds”=> TRUE等。 )。

我会定义函数是这样的:

function returnTimeInterval($startTime, $endTime, $interval, $options = array()) 
{ 
    // the first thing to do is merge options in with our defaults 
    $options = array_merge(array(
     "format" => "24-hour", 
     "include_seconds => TRUE 
     // etc. 
    ), $options); 

这使得功能可以再重写,这是很酷内默认的设置。当然,你需要注意那些奇怪的,未使用的选项没有被传入,但我会把它留给你。 :)

+0

'array_intersect_key()'将有助于避免未知选项。 – Walf 2014-04-11 07:01:07

2

或只是

function printArgs() { 

foreach (func_get_args() as $arg){ 
    echo $arg; 
} 
} 

printArgs("1 ", "2 ", "three "); 

输出1 2 three

2

虽然这个问题很老:其实在PHP 5.6+,你可以准确地写你写的:d