有没有一种在 PHP 中定义函数的方法,让你可以定义可变数量的参数?
我比较熟悉的语言中是这样的:
function myFunction(...rest){ /* rest == array of params */ return rest.length; }
myFunction("foo","bar"); // returns 2;
谢谢!
有没有一种在 PHP 中定义函数的方法,让你可以定义可变数量的参数?
我比较熟悉的语言中是这样的:
function myFunction(...rest){ /* rest == array of params */ return rest.length; }
myFunction("foo","bar"); // returns 2;
谢谢!
是的。使用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+ 版本中,现在可以使用可变函数参数:
<?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");
?>
只要有足够的参数来填充所有声明的参数,您可以接受任何函数的可变数量的参数。
<?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"
?>
虽然这个问题很旧:实际上在PHP 5.6+中,您可以完全按照您所写的方式编写代码:D
function printArgs() {
foreach (func_get_args () as $arg){
echo $arg;
}
}
printArgs("1 ", "2 ", "three ");
输出 1 2 three
我喜欢用类似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);
这允许在函数内设置默认值,这些默认值可以被覆盖,非常酷。当然,你需要小心不要传入奇怪、未使用的选项,但我会把这个留给你。:)
array_intersect_key()
将有助于避免未知选项。 - Walf$array = array();
$array[0] = "a";
$array[1] = 1;
myFunction($array);
func_get_args()
是你实际想用的,而不是这个冗长的第一种解决方案。 - Toskan