PHP 的 属性使用

等级 5477 次按键

定义和读取方法上的PHP 8属性元数据。

PHP 代码

// #[Attribute]让这个类成为属性(attribute)
// TARGET_METHOD表示只能用在方法上
1#[Attribute(Attribute::TARGET_METHOD)]
2class Route {
// 属性的参数会成为这些提升的属性
3 public function __construct(
4 public string $path,
5 public string $method = 'GET'
6 ) {}
7}
8
9class UserController {
// 给index()方法附加Route元数据
10 #[Route('/users', 'GET')]
11 public function index(): string {
12 return "User list";
13 }
14
// 路径相同,HTTP方法不同
15 #[Route('/users', 'POST')]
16 public function create(): string {
17 return "Create user";
18 }
19}
20
// 通过Reflection API读取属性
21$ref = new ReflectionMethod(UserController::class, 'index');
// 只返回Route对应的ReflectionAttribute对象
22$attrs = $ref->getAttributes(Route::class);
// newInstance()创建Route对象,输出/users
23echo $attrs[0]->newInstance()->path;

运行结果

/users
用这段代码练习打字

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

这段代码中的符号

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

  • '× 12
  • (× 9
  • )× 9
  • :× 8
  • $× 6
  • ;× 5
  • {× 5
  • }× 5
  • ,× 4
  • "× 4

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习