PHP 的 构造函数属性提升

等级 4206 次按键

使用构造函数属性提升(PHP 8.0)和 readonly 属性(PHP 8.1)简洁地定义 User 类,然后输出 email。

PHP 代码

1class User {
// 在参数上加可见性关键字即可同时声明并赋值属性
2 public function __construct(
// readonly:值只能设置一次,之后不能修改
3 public readonly string $name,
4 public readonly int $age,
5 public readonly string $email
// 属性提升完成了所有工作,因此函数体为空
6 ) {}
7}
8
// 参数依次赋给 $name、$age 和 $email
9$user = new User("Alice", 25, "alice@example.com");
// 读取是允许的,输出“alice@example.com”
10echo $user->email;

运行结果

alice@example.com
用这段代码练习打字

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

这段代码中的符号

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

  • $× 5
  • ,× 4
  • "× 4
  • _× 2
  • ;× 2
  • (× 2
  • )× 2
  • {× 2
  • }× 2
  • -× 1

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习