当前位置:Gxlcms > PHP教程 > php怎么获取方法的注释

php怎么获取方法的注释

时间:2021-07-01 10:21:17 帮助过:44人阅读

php获取方法的注释:首先打开相应的PHP文件;然后通过php中的反射机制,获取该类的文档注释;最后通过获取其所有的方法,获取方法的注释即可。

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑

php反射获取类和方法中的注释

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

所用到的主要类及其方法

  1. ReflectionClass
  2. ReflectionClass::getDocComment
  3. ReflectionClass::getMethods
  4. $method->getName()
  5. $method->getDocComment();
  6. $method->isProtected();
  7. $method->getParameters();
  8. $param->getName();
  9. $param->isDefaultValueAvailable();
  10. $param->getDefaultValue()

测试类如下:

test.php

  1. <?php
  2. header("Content-type: text/html; charset=utf-8");
  3. require_once dir(__DIR__).'function.php';
  4. require_once dir(__DIR__).'TestClass.php';
  5. $class_name = 'TestClass';
  6. $reflection = new ReflectionClass ( $class_name );
  7. //通过反射获取类的注释
  8. $doc = $reflection->getDocComment ();
  9. //解析类的注释头
  10. $parase_result = DocParserFactory::getInstance()->parse ( $doc );
  11. $class_metadata = $parase_result;
  12. //输出测试
  13. var_dump ( $doc );
  14. echo "\r\n";
  15. print_r( $parase_result );
  16. echo "\r\n-----------------------------------\r\n";
  17. //获取类中的方法,设置获取public,protected类型方法
  18. $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC + ReflectionMethod::IS_PROTECTED + ReflectionMethod::IS_PRIVATE);
  19. //遍历所有的方法
  20. foreach ($methods as $method) {
  21. //获取方法的注释
  22. $doc = $method->getDocComment();
  23. //解析注释
  24. $info = DocParserFactory::getInstance()->parse($doc);
  25. $metadata = $class_metadata + $info;
  26. //获取方法的类型
  27. $method_flag = $method->isProtected();//还可能是public,protected类型的
  28. //获取方法的参数
  29. $params = $method->getParameters();
  30. $position=0; //记录参数的次序
  31. foreach ($params as $param){
  32. $arguments[$param->getName()] = $position;
  33. //参数是否设置了默认参数,如果设置了,则获取其默认值
  34. $defaults[$position] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
  35. $position++;
  36. }
  37. $call = array(
  38. 'class_name'=>$class_name,
  39. 'method_name'=>$method->getName(),
  40. 'arguments'=>$arguments,
  41. 'defaults'=>$defaults,
  42. 'metadata'=>$metadata,
  43. 'method_flag'=>$method_flag
  44. );
  45. print_r($call);
  46. echo "\r\n-----------------------------------\r\n";
  47. }

function.php【推荐学习:《PHP视频教程》】

  1. <?php
  2. require_once dir(__DIR__).'DocParser.php';
  3. /**
  4. * 解析doc
  5. * 下面的DocParserFactory是对其的进一步封装,每次解析时,可以减少初始化DocParser的次数
  6. *
  7. * @param $php_doc_comment
  8. * @return array
  9. */
  10. function parse_doc($php_doc_comment) {
  11. $p = new DocParser ();
  12. return $p->parse ( $php_doc_comment );
  13. }
  14. /**
  15. * Class DocParserFactory 解析doc
  16. *
  17. * @example
  18. * DocParserFactory::getInstance()->parse($doc);
  19. */
  20. class DocParserFactory{
  21. private static $p;
  22. private function DocParserFactory(){
  23. }
  24. public static function getInstance(){
  25. if(self::$p == null){
  26. self::$p = new DocParser ();
  27. }
  28. return self::$p;
  29. }
  30. }

TestClass.php

  1. <?php
  2. /**
  3. * A test class 在此处不能添加@ur,@param,@return 注释
  4. * 如果要将类的注释和方法的注释合并的话,添加了上面的注释,会将方法中的注释给覆盖掉
  5. */
  6. class TestClass {
  7. /**
  8. * @desc 获取public方法
  9. *
  10. * @url GET pnrs
  11. * @param array $request_data
  12. * @return int id
  13. */
  14. public function getPublicMethod($no_default,$add_time = '0000-00-00') {
  15. echo "public";
  16. }
  17. /**
  18. * @desc 获取private方法
  19. *
  20. * @url GET private_test
  21. * @return int id
  22. */
  23. private function getPrivateMethod($no_default,$time = '0000-00-00') {
  24. echo "private";
  25. }
  26. /**
  27. * @desc 获取protected方法
  28. *
  29. * @url GET protected_test
  30. * @param $no_defalut,$time
  31. * @return int id
  32. */
  33. protected function getProtectedMethod($no_default,$time = '0000-00-00') {
  34. echo "protected";
  35. }
  36. }

DocParser.php 该类源自一个开源项目

  1. <?php
  2. /**
  3. * Parses the PHPDoc comments for metadata. Inspired by Documentor code base
  4. * @category Framework
  5. * @package restler
  6. * @subpackage helper
  7. * @author Murray Picton <info@murraypicton.com>
  8. * @author R.Arul Kumaran <arul@luracast.com>
  9. * @copyright 2010 Luracast
  10. * @license http://www.gnu.org/licenses/ GNU General Public License
  11. * @link https://github.com/murraypicton/Doqumentor
  12. */
  13. class DocParser {
  14. private $params = array ();
  15. function parse($doc = '') {
  16. if ($doc == '') {
  17. return $this->params;
  18. }
  19. // Get the comment
  20. if (preg_match ( '#^/\*\*(.*)\*/#s', $doc, $comment ) === false)
  21. return $this->params;
  22. $comment = trim ( $comment [1] );
  23. // Get all the lines and strip the * from the first character
  24. if (preg_match_all ( '#^\s*\*(.*)#m', $comment, $lines ) === false)
  25. return $this->params;
  26. $this->parseLines ( $lines [1] );
  27. return $this->params;
  28. }
  29. private function parseLines($lines) {
  30. foreach ( $lines as $line ) {
  31. $parsedLine = $this->parseLine ( $line ); // Parse the line
  32. if ($parsedLine === false && ! isset ( $this->params ['description'] )) {
  33. if (isset ( $desc )) {
  34. // Store the first line in the short description
  35. $this->params ['description'] = implode ( PHP_EOL, $desc );
  36. }
  37. $desc = array ();
  38. } elseif ($parsedLine !== false) {
  39. $desc [] = $parsedLine; // Store the line in the long description
  40. }
  41. }
  42. $desc = implode ( ' ', $desc );
  43. if (! empty ( $desc ))
  44. $this->params ['long_description'] = $desc;
  45. }
  46. private function parseLine($line) {
  47. // trim the whitespace from the line
  48. $line = trim ( $line );
  49. if (empty ( $line ))
  50. return false; // Empty line
  51. if (strpos ( $line, '@' ) === 0) {
  52. if (strpos ( $line, ' ' ) > 0) {
  53. // Get the parameter name
  54. $param = substr ( $line, 1, strpos ( $line, ' ' ) - 1 );
  55. $value = substr ( $line, strlen ( $param ) + 2 ); // Get the value
  56. } else {
  57. $param = substr ( $line, 1 );
  58. $value = '';
  59. }
  60. // Parse the line and return false if the parameter is valid
  61. if ($this->setParam ( $param, $value ))
  62. return false;
  63. }
  64. return $line;
  65. }
  66. private function setParam($param, $value) {
  67. if ($param == 'param' || $param == 'return')
  68. $value = $this->formatParamOrReturn ( $value );
  69. if ($param == 'class')
  70. list ( $param, $value ) = $this->formatClass ( $value );
  71. if (empty ( $this->params [$param] )) {
  72. $this->params [$param] = $value;
  73. } else if ($param == 'param') {
  74. $arr = array (
  75. $this->params [$param],
  76. $value
  77. );
  78. $this->params [$param] = $arr;
  79. } else {
  80. $this->params [$param] = $value + $this->params [$param];
  81. }
  82. return true;
  83. }
  84. private function formatClass($value) {
  85. $r = preg_split ( "[\(|\)]", $value );
  86. if (is_array ( $r )) {
  87. $param = $r [0];
  88. parse_str ( $r [1], $value );
  89. foreach ( $value as $key => $val ) {
  90. $val = explode ( ',', $val );
  91. if (count ( $val ) > 1)
  92. $value [$key] = $val;
  93. }
  94. } else {
  95. $param = 'Unknown';
  96. }
  97. return array (
  98. $param,
  99. $value
  100. );
  101. }
  102. private function formatParamOrReturn($string) {
  103. $pos = strpos ( $string, ' ' );
  104. $type = substr ( $string, 0, $pos );
  105. return '(' . $type . ')' . substr ( $string, $pos + 1 );
  106. }
  107. }

以上就是php怎么获取方法的注释的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行