(PHP 4, PHP 5, PHP 7, PHP 8)
func_get_arg — 返回參數(shù)列表的某一項(xiàng)
從用戶自定義函數(shù)的參數(shù)列表中獲取某個(gè)指定的參數(shù)。
該函數(shù)可以配合 func_get_args() 和 func_num_args() 一起使用,從而使得用戶自定義函數(shù)可以接受自定義個(gè)數(shù)的參數(shù)列表。
arg_num
參數(shù)的偏移量。函數(shù)的參數(shù)是從0開始計(jì)數(shù)的。
返回指定的參數(shù),錯(cuò)誤則返回 false
。
版本 | 說明 |
---|---|
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即可明白)
|
當(dāng)在自定義函數(shù)的外面調(diào)用的該函數(shù)的時(shí)候會(huì)發(fā)出一個(gè)警告,
或者是當(dāng) arg_num
比實(shí)際傳入的參數(shù)的數(shù)目大的時(shí)候也會(huì)發(fā)出一個(gè)警告。
示例 #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 前后對(duì)比的例子
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);
?>
以上例程會(huì)輸出:
注意:
因?yàn)楹瘮?shù)依賴于當(dāng)前作用域以確定參數(shù)的細(xì)節(jié),所以在 5.3.0 以前的版本中不能用作函數(shù)的參數(shù)。如必須傳遞此值時(shí),可將結(jié)果賦與一個(gè)變量,然后用此變量進(jìn)行傳遞。
注意:
如果參數(shù)以引用方式傳遞,函數(shù)對(duì)該參數(shù)的任何改變將在函數(shù)返回后保留。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.