我在PHP中有以下代码:
abstract class ProjectVars
{
/**
* Defines whether a user is logged in as ...
*/
const loggedInAs = [...];
[...]
}
我想访问字符串Defines whether a user is logged in as ...
。显然有更多的常量,我想得到所有常量的字符串。
那可能吗?使用反射类,我可以使用
$rc = new ReflectionClass('ProjectVars');
var_dump($rc->getDocComment());
获取整个班级的PHPDoc评论。我没有找到一个读取类常量的PHPDoc的相应方法。有没有办法做到这一点?
答案 0 :(得分:0)
是的,有:使用您已经知道的Reflection API,但是您可以通过创建一个输出所有注释的函数来进一步使用它。 然而,这种方法只是在问题类中创建一个静态方法,静态调用另一种方法是创建一个简单的辅助类,只有一个静态方法,它接受一个Argument(Class的名称)。下面的代码演示了两种方法:
<?php
abstract class ProjectVars {
/**
* Defines whether a user is logged in as ...
*/
protected $loggedIn;
/**
* Determines whether the user is registered or not
* @var bool;
*/
protected $register;
/**
* Holds information about user's surfing/visit history
* @var string;
*/
protected $records;
public static function getClassComments(){
$refClass = new ReflectionClass(self::class);
$comments = array();
foreach ($refClass->getProperties() as &$refProperty) {
$comments[$refProperty->getName()] = trim(preg_replace("#((\/)?(\*{1,2})(\/)?)#si", "", $refProperty->getDocComment()));
}
return $comments;
}
}
var_dump(ProjectVars::getClassComments());
// PRODUCES:
array (size=3)
'loggedIn' => string 'Defines whether a user is logged in as ...' (length=42)
'register' => string 'Determines whether the user is registered or not
@var bool;' (length=63)
'records' => string 'Holds information about user's surfingvisit history
@var string;' (length=68)
因此,要访问属性的所有评论,请说:loggedIn
或register
或records
,您可能需要做的就是:
ProjectVars::getClassComments()['loggedIn'];
ProjectVars::getClassComments()['register'];
ProjectVars::getClassComments()['records'];
第二种方法:使用简单的帮助类
<?php
class CommentAnalyser{
public static function getClassCommentsFor($fullyQualifiedClassName){
$refClass = new ReflectionClass($fullyQualifiedClassName);
$comments = array();
foreach ($refClass->getProperties() as &$refProperty) {
$comments[$refProperty->getName()] = trim(preg_replace("#((\/)?(\*{1,2})(\/)?)#si", "", $refProperty->getDocComment()));
}
return $comments;
}
}
var_dump(CommentAnalyser::getClassCommentsFor('ProjectVars'));
// PRODUCES:
array (size=3)
'loggedIn' => string 'Defines whether a user is logged in as ...' (length=42)
'register' => string 'Determines whether the user is registered or not
@var bool;' (length=63)
'records' => string 'Holds information about user's surfingvisit history
@var string;' (length=68)
模拟HERE。
干杯和好运......