當函數定義不指定參數個數時,可在函數內部使用這三個函數動態存取實際傳入的參數。
| 函數 | 回傳值 | 用途 |
|---|---|---|
func_get_args() | 陣列 | 取得所有參數組成的陣列 |
func_get_arg($index) | 混合型別 | 取得指定索引的參數值 |
func_num_args() | 整數 | 取得參數總個數 |
<?php
function demo() {
echo 'func_get_args(): ';
print_r(func_get_args());
echo '<br>func_get_arg(1): ' . func_get_arg(1);
echo '<br>func_num_args(): ' . func_num_args();
}
demo('www', 'jb51', 'net');
/*
輸出結果:
func_get_args(): Array ( [0] => www [1] => jb51 [2] => net )
func_get_arg(1): jb51
func_num_args(): 3
*/
?>
log($level, $message, ...$context)printf 的格式化函數class Product {
public function __construct() {
$args = func_get_args();
$count = func_num_args();
if ($count === 1 && is_array($args[0])) {
// 陣列初始化
$this->loadFromArray($args[0]);
} elseif ($count === 3) {
// 獨立參數初始化
list($this->id, $this->name, $this->price) = $args;
} else {
throw new InvalidArgumentException('參數錯誤');
}
}
}
... 可變參數語法(function(...$args)),語意更清晰且支援型別提示。func_get_arg() 索引超出範圍會產生警告並回傳 NULL。