PHP:使用可变参数计数定义函数?

JD *_*cks 12 php parameters php4 function

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

用我熟悉的语言是这样的:

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

myFunction("foo","bar"); // returns 2;
Run Code Online (Sandbox Code Playgroud)

谢谢!

Joh*_*nde 33

是.使用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");
?>
Run Code Online (Sandbox Code Playgroud)

在PHP 5.6+中,您现在可以使用可变参数函数:

<?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");
?>
Run Code Online (Sandbox Code Playgroud)

  • 非常确定`func_get_args()`是你真正想要使用的,而不是这个详细的第一个解决方案. (2认同)

mea*_*gar 6

您可以接受任意函数的可变数量的参数,只要有足够的参数填充所有声明的参数即可.

<?php

function test ($a, $b) { }

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

?>
Run Code Online (Sandbox Code Playgroud)

要访问传递给额外的未命名参数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"

?>
Run Code Online (Sandbox Code Playgroud)