func_get_args

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

func_get_args返回一個包含函數(shù)參數(shù)列表的數(shù)組

說明

func_get_args(): array

獲取函數(shù)參數(shù)列表的數(shù)組。

該函數(shù)可以配合 func_get_arg()func_num_args() 一起使用,從而使得用戶自定義函數(shù)可以接受自定義個數(shù)的參數(shù)列表。

返回值

返回一個數(shù)組,其中每個元素都是目前用戶自定義函數(shù)的參數(shù)列表的相應元素的副本。

更新日志

版本 說明
5.3.0 該函數(shù)可以在參數(shù)列表中使用。
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即可明白)

錯誤/異常

在用戶自定義函數(shù)外調(diào)用則會出現(xiàn)錯誤警告。

范例

示例 #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',
)

注釋

注意:

因為函數(shù)依賴于當前作用域以確定參數(shù)的細節(jié),所以在 5.3.0 以前的版本中不能用作函數(shù)的參數(shù)。如必須傳遞此值時,可將結(jié)果賦與一個變量,然后用此變量進行傳遞。

注意:

如果參數(shù)以引用方式傳遞,函數(shù)對該參數(shù)的任何改變將在函數(shù)返回后保留。As of PHP 7 the current values will also be returned if the arguments are passed by value.

注意: 該函數(shù)僅僅是返回傳遞參數(shù)的一個副本,并且不包含沒有傳入的默認參數(shù)。

參見