【问题标题】:fetch php method comments获取 php 方法注释
【发布时间】:2010-03-11 08:02:18
【问题描述】:

我想获取一个方法的cmets,以下面的方法为例:

/**
* Returns the regex to extract all inputs from a file.
* @param string The class name to search for.
* @return string The regex.
*/
public function method($param)
{
  //...
}

结果应该是

Returns the regex to extract all inputs from a file.
@param string The class name to search for.
@return string The regex.

我找到的方法是使用像 file_get_content 这样的函数来获取文件内容 -> 过滤我想要的方法 -> 使用正则表达式获取评论

好像有点复杂,有什么方便的存档方法吗?

【问题讨论】:

    标签: php comments methods


    【解决方案1】:

    实际上你可以通过 getDocComment 获取方法的 doc cmets

    $ref=new ReflectionMethod('className', 'methodName');
    
    echo $ref->getDocComment();
    

    【讨论】:

    • 这是正确的,但是如果您提到应该将文档注释包装在 /** */ 中以进行检索,然后如果方法上有多个 cmets,则只会返回最接近的注释。并且返回的字符串也包含评论星号和指向ReflectionClass::getDocComment 的链接以供进一步阅读。
    • 另请注意,在提出此问题时,您提到的方法不存在。
    【解决方案2】:

    如果你想在 PHP 中使用注释,请查看 php 中的 getDocComment reflection api

    【讨论】:

    • 深入了解后发现不是我需要的。 getDocComment 只是获取类的注释,而不是方法的。所以我写了一个小脚本来做到这一点gist.github.com/329113
    【解决方案3】:

    PHP 文档。喜欢 Java 文档。

    【讨论】:

      【解决方案4】:

      对于方法转储,我使用我编写的这个小函数。 它从提供的类中获取所有公开的(因此对您有用)的方法。

      我个人使用 dump() 方法来很好地格式化输出的方法名称和描述数组,但如果您希望将其用于其他用途,则不需要这样做:-)

      function getDocumentation($inspectclass) {
          /** Get a list of all methods */
          $methods = get_class_methods($inspectclass);
          /** Get the class name */
          $class =get_class($inspectclass);
          $arr = [];
          foreach($methods as $method) {
              $ref=new ReflectionMethod( $class, $method);
              /** No use getting private methods */
              if($ref->isPublic()) {
                  $arr[$method] = $ref->getDocComment();
              }
          }
          /** dump is a formatting function I use, feel free to use your own */
          return dump($arr);
      }
      echo getDocumentation($this);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-15
        • 2014-02-12
        相关资源
        最近更新 更多