通过php中的反射机制,获取该类的文档注释,再通过获取其所有的方法,获取方法的注释

所用到的主要类及其方法

ReflectionClass
ReflectionClass::getDocComment
ReflectionClass::getMethods $method->getName()
$method->getDocComment();
$method->isProtected();
$method->getParameters(); $param->getName();
$param->isDefaultValueAvailable();
$param->getDefaultValue()

测试类如下:

test.php

<?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

<?php
require_once dir(__DIR__).'DocParser.php'; /**
* 解析doc
* 下面的DocParserFactory是对其的进一步封装,每次解析时,可以减少初始化DocParser的次数
*
* @param $php_doc_comment
* @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

<?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.com>
* @author R.Arul Kumaran <arul@luracast.com>
* @copyright 2010 Luracast
* @license http://www.gnu.org/licenses/ GNU General Public License
* @link https://github.com/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
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;
}
private function formatClass($value) {
$r = preg_split ( "[\(|\)]", $value );
if (is_array ( $r )) {
$param = $r [0];
parse_str ( $r [1], $value );
foreach ( $value as $key => $val ) {
$val = explode ( ',', $val );
if (count ( $val ) > 1)
$value [$key] = $val;
}
} else {
$param = 'Unknown';
}
return array (
$param,
$value
);
}
private function formatParamOrReturn($string) {
$pos = strpos ( $string, ' ' ); $type = substr ( $string, 0, $pos );
return '(' . $type . ')' . substr ( $string, $pos + 1 );
}
}

转: https://blog.csdn.net/my_yang/article/details/43882661

php反射获取类和方法中的注释的更多相关文章

  1. Java反射学习-1 - 反射获取类的属性,方法,构造器

    新建一个Person类 package cn.tx.reflect; /** * 注解初步了解 * @author Administrator * */ public class Person { p ...

  2. java反射-使用反射获取类的所有信息

    在OOP(面向对象)语言中,最重要的一个概念就是:万事万物皆对象. 在java中,类也是一个对象,是java.lang.Class的实例对象,官网称该对象为类的类类型. Class 类的实例表示正在运 ...

  3. Java反射学习-3 - 反射获取属性,方法,构造器

    package cn.tx.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import ...

  4. java 通过反射获取类属性结构,类方法,类父类及其泛型,类,接口和包

    首先自定义三个类 package reflection1; public interface MtInterface { void info(); } package reflection1; imp ...

  5. c#通过反射获取类上的自定义特性

    c#通过反射获取类上的自定义特性 本文转载:http://www.cnblogs.com/jeffwongishandsome/archive/2009/11/18/1602825.html 下面这个 ...

  6. java利用反射获取类的属性及类型

    java利用反射获取类的属性及类型. import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.Map ...

  7. c++ 类覆盖方法中的协变返回类型

    c++ 类覆盖方法中的协变返回类型 在C++中,只要原来的返回类型是指向类的指针或引用,新的返回类型是指向派生类的指针或引用,覆盖的方法就可以改变返回类型.这样的类型称为协变返回类型(Covarian ...

  8. C#通过反射调用类及方法

    反射有个典型的应用,就是菜单的动态加载,原理就是通过反射调用某个窗体(类).下面演示一下通过反射调用类及方法: 1.新建一个类,命名为:ReflectionHelper,代码如下: #region 创 ...

  9. idea中查看方法参数;查看类、方法、属性注释

    Ctrl+P:查看方法参数Ctrl+Q:查看类.方法.属性注释

随机推荐

  1. 使用JAVA的URL类处理url事例

    import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) ...

  2. FILTER——JAVA

    一.概念 Filter也称之为过滤器,它是Servlet技术中比较激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或 ...

  3. SSH使用Slf4j

    1. Slf4j的使用 在上一篇随笔:SSH使用Log4j的基础上配置. (1)导入两个文件:slf4j-api-1.5.8.jar和slf4j-log4j12-1.5.8.jar. (2)在需要日志 ...

  4. 解决 Out of range value adjusted for column 'ID' at row 1

    MySQL升级到5.0.17后,在执行sql语句INSERT INTO `news` (`ID`, `Title`, `Content`) VALUES ('', '标题', '正文');时出现错误: ...

  5. Python实现微信扫码支付模式二(NativePay)

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/7649207.html 核心代码github地址:https://github.com/ygj0930/Pyth ...

  6. 排序基础之非比较的计数排序、桶排序、基数排序(Java实现)

    转载请注明原文地址: http://www.cnblogs.com/ygj0930/p/6639353.html  比较和非比较排序 快速排序.归并排序.堆排序.冒泡排序等比较排序,每个数都必须和其他 ...

  7. Valid Number 验证数字

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

  8. GoldenGate安装与卸载

    软件下载 http://www.oracle.com/technetwork/middleware/goldengate/downloads/index.html 安装 卸载(Using Oracle ...

  9. V-rep学习笔记:Reflexxes Motion Library 1

    V-REP中集成了在线运动轨迹生成库Reflexxes Motion Library Type IV,目前Reflexxes公司已经被谷歌收购.(The Reflexxes Motion Librar ...

  10. DLib Http Server程序示例

    /* 这个示例是一个使用了Dlib C++ 库的server组件的HTTP扩展 它创建一个始终以简单的HTML表单为响应的服务器. 要查看这个页面,你应该访问 http://localhost:500 ...