php反射获取类和⽅法中的注释通过php中的反射机制,获取该类的⽂档注释,再通过获取其所有的⽅法,获取⽅法的注释
所⽤到的主要类及其⽅法
ReflectionClass
ReflectionClass::getDocComment
ReflectionClass::getMethods
$method->getName()
$method->getDocComment();
$method->isProtected();
$method->getParameters();
$param->getName();
$param->isDefaultValueAvailable();
$param->getDefaultValue()
测试类如下:
test.php
header("Content-type: text/html; charset=utf-8");
require_once dir(__DIR__).'function.php';
require_once dir(__DIR__).'TestClass.php';
$class_name = 'TestClass';
$reflection = new ReflectionClass ( $class_name );
//通过反射获取类的注释
$doc = $reflection->getDocComment ();
//解析类的注释头
$parase_result =  DocParserFactory::getInstance()->parse ( $doc );
$class_metadata = $parase_result;
//输出测试
var_dump ( $doc );
echo "\r\n";
print_r( $parase_result );
echo "\r\n-----------------------------------\r\n";
//获取类中的⽅法,设置获取public,protected类型⽅法
$methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC + ReflectionMethod::IS_PROTECTED + ReflectionMethod::IS_PRIVATE); //遍历所有的⽅法
foreach ($methods as $method) {
//获取⽅法的注释
$doc = $method->getDocComment();
//解析注释
$info = DocParserFactory::getInstance()->parse($doc);
$metadata = $class_metadata +  $info;
//获取⽅法的类型
$method_flag = $method->isProtected();//还可能是public,protected类型的
//获取⽅法的参数
$params = $method->getParameters();
$position=0;    //记录参数的次序
foreach ($params as $param){
$arguments[$param->getName()] = $position;
/
/参数是否设置了默认参数,如果设置了,则获取其默认值
$defaults[$position] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
$position++;
}
$call = array(
'class_name'=>$class_name,
'method_name'=>$method->getName(),
'arguments'=>$arguments,
'defaults'=>$defaults,
'metadata'=>$metadata,
'method_flag'=>$method_flag
)
;
print_r($call);
echo "\r\n-----------------------------------\r\n";
}
function.php
require_once dir(__DIR__).'DocParser.php';
/**
* 解析doc
* 下⾯的DocParserFactory是对其的进⼀步封装,每次解析时,可以减少初始化DocParser的次数 *
* @param $php_doc_comment
php中header是什么意思* @return array
*/
function parse_doc($php_doc_comment) {
$p = new DocParser ();
return $p->parse ( $php_doc_comment );
}
/**
* Class DocParserFactory 解析doc
*
* @example
*      DocParserFactory::getInstance()->parse($doc);
*/
class DocParserFactory{
private static $p;
private function DocParserFactory(){
}
public static function getInstance(){
if(self::$p == null){
self::$p = new DocParser ();
}
return self::$p;
}
}
TestClass.php
/**
* A test class  在此处不能添加@ur,@param,@return 注释
*  如果要将类的注释和⽅法的注释合并的话,添加了上⾯的注释,会将⽅法中的注释给覆盖掉 */
class TestClass {
/**
* @desc 获取public⽅法
*
* @url GET pnrs
* @param array $request_data
* @return int id
*/
public function getPublicMethod($no_default,$add_time = '0000-00-00') {
echo "public";
}
/**
* @desc 获取private⽅法
*
* @url GET private_test
* @return int id
*/
private function getPrivateMethod($no_default,$time = '0000-00-00') {
echo "private";
}
/**
* @desc 获取protected⽅法
*
* @url GET protected_test
* @param $no_defalut,$time
* @return int id
*/
protected function getProtectedMethod($no_default,$time = '0000-00-00') {
echo "protected";
}
}
DocParser.php  该类源⾃⼀个开源项⽬
<?php
/**
* Parses the PHPDoc comments for metadata. Inspired by Documentor code base
* @category  Framework
* @package    restler
* @subpackage helper
* @author    Murray Picton <info@murraypicton>
* @author    R.Arul Kumaran <arul@luracast>
* @copyright  2010 Luracast
* @license    /licenses/ GNU General Public License
* @link      github/murraypicton/Doqumentor
*/
class DocParser {
private $params = array ();
function parse($doc = '') {
if ($doc == '') {
return $this->params;
}
// Get the comment
if (preg_match ( '#^/\*\*(.*)\*/#s', $doc, $comment ) === false)
return $this->params;
$comment = trim ( $comment [1] );
// Get all the lines and strip the * from the first character
// Get all the lines and strip the * from the first character
if (preg_match_all ( '#^\s*\*(.*)#m', $comment, $lines ) === false)
return $this->params;
$this->parseLines ( $lines [1] );
return $this->params;
}
private function parseLines($lines) {
foreach ( $lines as $line ) {
$parsedLine = $this->parseLine ( $line ); // Parse the line
if ($parsedLine === false && ! isset ( $this->params ['description'] )) {    if (isset ( $desc )) {
// Store the first line in the short description
$this->params ['description'] = implode ( PHP_EOL, $desc );
}
$desc = array ();
} elseif ($parsedLine !== false) {
$desc [] = $parsedLine; // Store the line in the long description
}
}
$desc = implode ( ' ', $desc );
if (! empty ( $desc ))
$this->params ['long_description'] = $desc;
}
private function parseLine($line) {
// trim the whitespace from the line
$line = trim ( $line );
if (empty ( $line ))
return false; // Empty line
if (strpos ( $line, '@' ) === 0) {
if (strpos ( $line, ' ' ) > 0) {
/
/ Get the parameter name
$param = substr ( $line, 1, strpos ( $line, ' ' ) - 1 );
$value = substr ( $line, strlen ( $param ) + 2 ); // Get the value
} else {
$param = substr ( $line, 1 );
$value = '';
}
// Parse the line and return false if the parameter is valid
if ($this->setParam ( $param, $value ))
return false;
}
return $line;
}
private function setParam($param, $value) {
if ($param == 'param' || $param == 'return')
$value = $this->formatParamOrReturn ( $value );
if ($param == 'class')
list ( $param, $value ) = $this->formatClass ( $value );
if (empty ( $this->params [$param] )) {
$this->params [$param] = $value;
} else if ($param == 'param') {
$arr = array (
$this->params [$param],
$value
);
$this->params [$param] = $arr;
} else {
$this->params [$param] = $value + $this->params [$param];
}
return true;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。