func_get_args

(PHP 4, PHP 5, PHP 7, PHP 8)

func_get_args返回一个包含函数参数列表的数组

说明

func_get_args ( ) : array

获取函数参数列表的数组。

该函数可以配合 func_get_arg()func_num_args() 一起使用,从而使得用户自定义函数可以接受自定义个数的参数列表。

返回值

返回一个数组,其中每个元素都是目前用户自定义函数的参数列表的相应元素的副本。

更新日志

版本 说明
5.3.0 该函数可以在参数列表中使用。
5.3.0 If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns false. (不知道如何翻译跟好,直接参考例2即可明白)

错误/异常

在用户自定义函数外调用则会出现错误警告。

范例

示例 #1 func_get_args() 例子

<?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(123);
?>

以上例程会输出:

Number of arguments: 3<br />
Second argument is: 2<br />
Argument 0 is: 1<br />
Argument 1 is: 2<br />
Argument 2 is: 3<br />

示例 #2 PHP 5.3 前后使用 func_get_args() 在的对比

test.php
<?php
function foo() {
    include 
'./fga.inc';
}

foo('First arg''Second arg');
?>

fga.inc
<?php

$args 
func_get_args();
var_export($args);

?>

PHP 5.3 版本之前的输出:

array (
  0 => 'First arg',
  1 => 'Second arg',
)

PHP 5.3 和之后的版本的输出:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

示例 #3 func_get_args() example of byref and byval arguments

<?php
function byVal($arg) {
    echo 
'As passed     : 'var_export(func_get_args()), PHP_EOL;
    
$arg 'baz';
    echo 
'After change  : 'var_export(func_get_args()), PHP_EOL;
}

function 
byRef(&$arg) {
    echo 
'As passed     : 'var_export(func_get_args()), PHP_EOL;
    
$arg 'baz';
    echo 
'After change  : 'var_export(func_get_args()), PHP_EOL;
}

$arg 'bar';
byVal($arg);
byRef($arg);
?>

以上例程会输出:


As passed : array (
0 => 'bar',
)
After change : array (
0 => 'bar',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

注释

注意:

因为函数依赖于当前作用域以确定参数的细节,所以在 5.3.0 以前的版本中不能用作函数的参数。如必须传递此值时,可将结果赋与一个变量,然后用此变量进行传递。

注意:

如果参数以引用方式传递,函数对该参数的任何改变将在函数返回后保留。As of PHP 7 the current values will also be returned if the arguments are passed by value.

注意: 该函数仅仅是返回传递参数的一个副本,并且不包含没有传入的默认参数。

参见