php 随意参数方法的使用
1, 用到的PHP函数: func_get_arg() / func_get_args()/ func_num_args
2, func_get_arg(index) :根据索引取得参数具体值
<?php
function foo() { $numargs = func_num_args(); echo "Number of arguments: $numargs<br />\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "<br />\n"; } } foo (1, 2, 3); ?>
3, func_get_args(); 取得所有传入的参数,并以数组的方式反回;
// yes, the argument list can be empty
function foo() { // returns an array of all passed arguments $args = func_get_args(); foreach ($args as $k => $v) { echo “arg”.($k+1).”: $v\n”; } } foo(); /* 没用任何输出*/ foo(‘hello’); /* 输出 arg1: hello */ foo(‘hello’, ‘world’, ‘again’); /*输出 arg1: hello arg2: world arg3: again */
4, func_num_args(); 取得传入参数的个数;
<?
function foo() { $numargs = func_num_args(); echo “Number of arguments: $numargs\n“; } foo(1, 2, 3); // Prints ‘Number of arguments: 3′ ?>
5, 综合实例
<?php
function foo() { $numargs = func_num_args();//得到参数的个数 echo "Number of arguments: $numargs<br />\n"; if ($numargs >= 2) { echo "Second argument is: " . func_get_arg(1) . "<br />\n"; } $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo "Argument $i is: " . $arg_list[$i] . "<br />\n"; } } foo(1, 2, 3); ?>