我用一个静态方法编写了这个类,该方法读取注释并将它们转换为一个数组。所以,这段代码:
/**
* @MyAnnotation(attr1=value,attr2=value);
*/
class MyClass
{
public static function readMyAnnotation()
{
$classComment = (new ReflectionClass(get_class()))->getDocComment();
$comments = explode("\n", $classComment);
foreach ($comments as $item) {
if(strpos($item, "@")) {
$comment = explode("@", $item);
$annotation = explode(")", $comment[1])[0];
$annotationName = explode("(", $annotation)[0];
$annotationValue = explode("(", $annotation)[1];
$annotationParams = explode(",", $annotationValue);
$params = [];
foreach ($annotationParams as $item) {
$params[explode("=", $item)[0]] = explode("=", $item)[1];
}
print_r([$annotationName => $params]);
}
}
}
}
MyClass::readMyAnnotation();
将输出:
Array ( [MyAnnotation] => Array ( [attr1] => value [attr2] => value ) );
有人可以帮助我使用正则表达式优化此代码吗?我无法用正则表达式编写好的代码。我的代码工作正常,但我不喜欢它!
/**
* @MyAnnotation(attr1=value,attr2=value);
*/
class MyClass
{
public static function readMyAnnotation()
{
$classComment = (new ReflectionClass(get_class()))->getDocComment();
$comments = explode("\n", $classComment);
foreach ($comments as $item) {
if(strpos($item, "@")) {
/* ?????????????? */
print_r([$annotationName => $params]);
}
}
}
}