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)
您可以接受任意函数的可变数量的参数,只要有足够的参数填充所有声明的参数即可.
<?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)