| 函式 | 回傳值 | 用途 |
|---|---|---|
| int | 取得呼叫時實際傳入參數個數 | |
| mixed | 取得指定索引(0 起)的參數值 | |
| array | 取得所有參數組成的陣列 |
三者皆只能在使用者自訂函式內部呼叫,外部呼叫會觸發警告。
function foo() {
$num = func_num_args();
echo "參數個數: $num\n";
if ($num >= 2) {
echo "第 2 個參數: " . func_get_arg(1) . "\n";
}
$all = func_get_args();
foreach ($all as $i => $v) {
echo "參數 $i: $v\n";
}
}
foo(1, 2, 3);
/* 輸出:
參數個數: 3
第 2 個參數: 2
參數 0: 1
參數 1: 2
參數 2: 3 */
class MyDB {
private $host, $user, $pass, $db;
public function __construct() {
$n = func_num_args();
if ($n === 0) return; // 允許無參數建構,稍後 init()
$args = func_get_args();
// 支援三種呼叫方式:
// new MyDB('host', 'user', 'pass', 'db')
// new MyDB(['host'=>..., 'user'=>..., 'pass'=>..., 'db'=>...])
// new MyDB($configObj)
if ($n === 1 && is_array($args[0])) {
$cfg = $args[0];
} elseif ($n >= 3) {
$cfg = ['host'=>$args[0], 'user'=>$args[1], 'pass'=>$args[2], 'db'=>$args[3]??''];
} else {
throw new InvalidArgumentException('Invalid arguments');
}
$this->host = $cfg['host'];
$this->user = $cfg['user'];
$this->pass = $cfg['pass'];
$this->db = $cfg['db'];
$this->connect();
}
// ...
}
現代 PHP 建議使用 ...$args 取代三函式,語意更清晰、效能更好:
function modernFoo(...$args) {
echo "個數: " . count($args) . "\n";
echo "第二個: " . ($args[1] ?? '無') . "\n";
print_r($args);
}
modernFoo(1, 2, 3); // 相同效果
fn() => ...)中使用;func_get_arg() 索引超界會產生警告並回傳 false;function(&$a))在 func_get_args() 回傳的陣列中為值複製,非引用;...$args。