php 7 注解实现
PHP 7 注解实现方法
PHP 7 引入了一种通过注释(DocBlock)实现类似注解功能的方式,虽然原生不支持注解语法,但可以通过反射和第三方库(如Doctrine Annotations)实现类似效果。
使用 Doctrine Annotations 库
安装 Doctrine Annotations 库:
composer require doctrine/annotations
定义自定义注解类:
use Doctrine\Common\Annotations\Annotation;
/
* @Annotation
* @Target("CLASS")
*/
class MyAnnotation
{
public $value;
}
在目标类上使用注解:

/
* @MyAnnotation("example_value")
*/
class MyClass
{
}
通过反射读取注解:
use Doctrine\Common\Annotations\AnnotationReader;
$reader = new AnnotationReader();
$reflectionClass = new ReflectionClass('MyClass');
$annotation = $reader->getClassAnnotation($reflectionClass, 'MyAnnotation');
echo $annotation->value; // 输出: example_value
使用 PHP 原生反射和 DocBlock
创建自定义解析逻辑:

class MyParser
{
public static function parse($className)
{
$reflection = new ReflectionClass($className);
$docComment = $reflection->getDocComment();
if (preg_match('/@MyCustomAnnotation\(([^)]+)\)/', $docComment, $matches)) {
return $matches[1];
}
return null;
}
}
在类上添加自定义注释:
/
* @MyCustomAnnotation("custom_value")
*/
class MyClass
{
}
解析注释内容:
$value = MyParser::parse('MyClass');
echo $value; // 输出: custom_value
注意事项
PHP 8 开始原生支持注解(Attribute),语法更简洁:
#[MyAnnotation('example_value')]
class MyClass
{
}
如需在PHP 7中实现类似功能,建议使用Doctrine Annotations等成熟库,而非自行解析DocBlock。






