func_get_arg

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

func_get_arg返回參數列表的某一項

說明

func_get_arg(int $arg_num): mixed

從用戶自定義函數的參數列表中獲取某個指定的參數。

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

參數

arg_num

參數的偏移量。函數的參數是從0開始計數的。

返回值

返回指定的參數,錯誤則返回 false 。

更新日志

版本 說明
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即可明白)

錯誤/異常

當在自定義函數的外面調用的該函數的時候會發(fā)出一個警告, 或者是當 arg_num 比實際傳入的參數的數目大的時候也會發(fā)出一個警告。

范例

示例 #1 func_get_arg() 例子

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

示例 #2 func_get_arg() PHP 5.3 前后對比的例子

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

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

fga.inc
<?php

$arg 
func_get_arg(1);
var_export($arg);

?>

PHP 5.3 版本之前的輸出:

'Second arg'

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

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

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

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

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

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

以上例程會輸出:


As passed : 'bar'
After change : 'bar'
As passed : 'bar'
After change : 'baz'

注釋

注意:

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

注意:

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

注意: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

參見