PHP 命名参数
掌握 PHP 8 命名参数特性,跳过可选参数,提高函数调用可读性。 · 难度:入门 · +15XP
命名参数概述
PHP 8 引入了命名参数(Named Arguments),允许在调用函数时按参数名传递值,而非仅按位置。
基本用法
function createUser(string $name, int $age, string $country = 'China', bool $active = true) {
// ...
}
// 传统方式
createUser('Alice', 25, 'USA', false);
// 命名参数
createUser(name: 'Alice', age: 25, active: false);
跳过可选参数
createUser(name: 'Bob', age: 30); // 省略 country 和 active
与默认值结合
function greet(string $name, string $greeting = 'Hello', bool $shout = false): string {
$msg = "$greeting, $name";
return $shout ? strtoupper($msg) : $msg;
}
echo greet(name: 'World', shout: true); // HELLO, WORLD
| 优势 | 说明 |
|---|---|
| 可读性 | 明确参数含义 |
| 灵活性 | 只传递需要的参数 |
| 兼容性 | 与位置参数可混合使用 |
练习提示
调用下面的函数,只传递 name 和 email,不传递其他参数。