func_get_arg
(PHP 4, PHP 5, PHP 7, PHP 8)
func_get_arg — 返回參數列表的某一項
說明
從使用者自定義函式的參數列表中獲取某個指定的參數。
該函式可以配合 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即可明白)
|
錯誤/異常
當在自定義函式的外面呼叫的該函式的時候會發出一個警告,
或者是當 arg_num
比實際傳入的參數的數目大的時候也會發出一個警告。
範例
示例 #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 (1, 2, 3);
?>
示例 #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'
註釋
注意:
因為函式依賴於目前作用域以確定參數的細節,所以在 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.
參見
- func_get_args() - 返回一個包含函式參數列表的陣列
- func_num_args() - Returns the number of arguments passed to the function