php 注解实现
PHP 注解实现方法
PHP 注解(Annotations)通过反射机制实现,常用于框架中标记路由、依赖注入等。PHP 原生不支持注解,需借助第三方库或 PHP 8+ 原生特性。

使用 PHP 8+ 原生注解
PHP 8 引入原生注解(Attributes),语法为 #[...],需通过反射读取。

#[Attribute]
class Route {
public function __construct(public string $path) {}
}
#[Route('/home')]
class HomeController {
#[Route('/index')]
public function index() {}
}
// 反射读取注解
$reflectionClass = new ReflectionClass('HomeController');
$attributes = $reflectionClass->getAttributes(Route::class);
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
echo $route->path; // 输出 '/home'
}
使用 Doctrine Annotations 库
适用于 PHP 7+,需通过 Composer 安装 doctrine/annotations。
use Doctrine\Common\Annotations\AnnotationReader;
/
* @Annotation
* @Target("CLASS")
*/
class Route {
public $path;
}
/
* @Route(path="/home")
*/
class HomeController {}
$reader = new AnnotationReader();
$reflectionClass = new ReflectionClass('HomeController');
$route = $reader->getClassAnnotation($reflectionClass, Route::class);
echo $route->path; // 输出 '/home'
自定义注解解析
若需手动解析文档块中的注解,可通过正则表达式提取。
class CustomAnnotationParser {
public static function parse($className) {
$reflection = new ReflectionClass($className);
$docComment = $reflection->getDocComment();
preg_match('/@Route\(path="(.+?)"\)/', $docComment, $matches);
return $matches[1] ?? null;
}
}
// 使用示例
$path = CustomAnnotationParser::parse('HomeController');
echo $path; // 输出 '/home'
注意事项
- PHP 8+ 原生注解性能更高,推荐新项目使用。
- Doctrine Annotations 兼容性更好,适合旧项目。
- 自定义解析灵活性高,但维护成本较大。






