在PHP中使用无限参数的函数

时间:2012-05-29 16:38:51

标签: php function

我只想制作像array_merge ( array $array1 [, array $... ] )这样的功能 或简单的函数,如myfunc($st1, $st2, $st3, $st4, $st5, etc)

function make_my_merge($) {
     ..... operation to be performed ......
}

4 个答案:

答案 0 :(得分:3)

使用func_get_args()访问传递给函数的所有参数(作为数组)。此外,您可以使用func_num_args()来计算传入的所有参数。

function make_my_merge () {
    if ( func_num_args() ) {
        $args = func_get_args();
        echo join( ", ", $args );
    }
}

// Foo, Bar
make_my_merge("Foo", "Bar");

// Foo, Bar, Fizz, Buzz
make_my_merge("Foo", "Bar", "Fizz", "Buzz");

键盘:http://codepad.org/Dk7MD18I

答案 1 :(得分:0)

使用func_get_args()

function make_my_merge() {
  $args = func_get_args();

  foreach ($args as $arg) {
    echo "Arg: $arg\n";
  }

}

可以看出,你通过func_get_args()函数获得了传递给你的函数的所有参数,它返回一个数组,你可以使用each迭代它来处理传递的每个参数。

答案 2 :(得分:0)

这应该有所帮助:PHP Function Variable Arguments

答案 3 :(得分:0)

你永远不会知道你想要多少个参数......所以你不能在我的opimion中定义具有无限参数的精确函数。但我建议在函数中传递2个参数,一个作为数组中的索引或值以及其他数组本身....它就像这样

<?php
$arr = array('val1','val2','val3',.....);
$count = count($arr);
$result = your_function($count,$arr);
?> 

你的函数看起来像是在顶部或其他php文件或类

上的某个地方
<?php
function your_function($count,$arr)
{
   //Here you know the number of values you have in array as $count
   //So you can use for loop or others to merge or for other operations
   for($i=0;$i<$count;$i++)
   {
          //Some operation
   }
}
?>
相关问题