PHP 的 命名参数

等级 5268 次按键

使用命名参数以任意顺序传递参数。

PHP 代码

// $age和$active有默认值,因此可以省略
1function createUser(
2 string $name,
3 string $email,
4 int $age = 0,
5 bool $active = true
6): string {
// 把布尔值转换为文字
7 $status = $active ? "active" : "inactive";
// 用字符串插值拼出结果
8 return "$name ($email), Age: $age, Status: $status";
9}
// 命名参数(PHP 8.0+)可以按任意顺序传递
// 输出John (john@example.com), Age: 0, Status: inactive
10echo createUser(
11 email: "john@example.com",
12 name: "John",
// 省略了$age,保持默认值0
13 active: false
14);

运行结果

John (john@example.com), Age: 0, Status: inactive
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • "× 10
  • $× 10
  • ,× 7
  • :× 7
  • ;× 3
  • (× 3
  • )× 3
  • =× 3
  • ?× 1
  • .× 1

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习