<?php
#[Attribute] // 定义注解 有不同类型 往下看
class Annotation {
public string $msg;
public function __construct()
{
echo "注解初始化\r\n";
}
public function set($key, $value)
{
$this -> $key = $value;
}
public function get($key) {
return $this -> $key ?? null;
}
}
class b{
#[Annotation] //使用注解
public function c() {
# 通过反射实例化 类 并获得 方法所绑定的类 注解 是可以绑定多个的 所以getAttributes 返回的数组 通过指定下标 获取 注解类 实例化就行了
$ref = new ReflectionClass(a::class);
$ref = $ref -> getMethod('c') ->getAttributes('a')[0] -> newInstance();
$ref -> set('woto', '123');
var_dump($ref -> get('woto'));
}
}
(new b()) -> c();
// 可定义注解类型
/*
例子: [Attribute(Attribute::TARGET_CLASS)]
TARGET_CLASS //类的注解类
TARGET_FUNCTION //函数注解类
TARGET_METHOD //方法注解类
TARGET_PROPERTY //属性注解类
TARGET_CLASS_CONSTANT //类常量注解类
TARGET_PARAMETER //参数注解类
TARGET_ALL
*/