php注解实现
PHP 注解实现方法
PHP 注解(Annotations)可以通过多种方式实现,主要依赖反射(Reflection)和文档块(DocBlock)解析。以下是常见的实现方法:
使用 Doctrine Annotations 库
Doctrine Annotations 是 PHP 生态中广泛使用的注解解析库,支持通过文档块定义和解析注解。
安装 Doctrine Annotations:
composer require doctrine/annotations
定义注解类:
use Doctrine\Common\Annotations\Annotation;
/
* @Annotation
* @Target("CLASS")
*/
class MyAnnotation
{
public $value;
}
使用注解:
/
* @MyAnnotation("example")
*/
class MyClass
{
}
解析注解:
use Doctrine\Common\Annotations\AnnotationReader;
$reader = new AnnotationReader();
$reflectionClass = new ReflectionClass('MyClass');
$annotation = $reader->getClassAnnotation($reflectionClass, 'MyAnnotation');
echo $annotation->value; // 输出 "example"
使用 PHP 8 原生注解(Attributes)
PHP 8 引入了原生注解(Attributes),语法更简洁,性能更好。
定义 Attribute:
#[Attribute(Attribute::TARGET_CLASS)]
class MyAttribute
{
public function __construct(public string $value) {}
}
使用 Attribute:
#[MyAttribute("example")]
class MyClass
{
}
解析 Attribute:
$reflectionClass = new ReflectionClass('MyClass');
$attributes = $reflectionClass->getAttributes(MyAttribute::class);
foreach ($attributes as $attribute) {
$instance = $attribute->newInstance();
echo $instance->value; // 输出 "example"
}
自定义注解解析
如果不想依赖第三方库,可以手动解析文档块实现注解功能。
定义注解解析器:
function parseAnnotations($docComment)
{
preg_match_all('/@(\w+)(?:\s*(?:\(\s*)?(.*?)(?:\s*\))?)?\s*(?:\n|\*\/)/', $docComment, $matches);
$annotations = [];
foreach ($matches[1] as $i => $name) {
$annotations[$name][] = $matches[2][$i];
}
return $annotations;
}
使用示例:
/
* @MyAnnotation("test")
* @AnotherAnnotation
*/
class MyClass
{
}
$reflectionClass = new ReflectionClass('MyClass');
$annotations = parseAnnotations($reflectionClass->getDocComment());
print_r($annotations);
性能考虑
- Doctrine Annotations 功能全面但性能较低
- PHP 8 Attributes 是原生实现,性能最佳
- 自定义解析灵活性高但需要处理各种边界情况
根据项目需求选择合适的实现方式,PHP 8+ 项目推荐使用原生 Attributes。







