displayabc
V2EX  ›  PHP

如何获取 php 文档注释的某个字段?

  •  
  •   displayabc · Apr 11, 2016 · 4668 views
    This topic created in 3709 days ago, the information mentioned may be changed or developed.
    @author  Author Name [<[email protected]>]      代码编写人(负责人)
    @version xx.xx                                 当前版本号
    @param   datatype $v_name[,...] description    函数相关联的参数,含有,...表示可传入不定数量的其他参数
    @return  datatype description                  函数或方法的返回值类型
    @var     datatype                              在类中说明类变量(属性)的类型
    @example [path|url] description                举一个例子,以阐释使用方法
    @todo    description                           待完成的工作信息或待解决的问题信息
    

    现在已经通过反射获取到方法的文档注释,要怎么获取文档注释的特定内容,比如我现在要获取所有 @param 的,怎么获取?

    9 replies    2016-04-21 13:05:16 +08:00
    feiyuanqiu
        1
    feiyuanqiu  
       Apr 11, 2016   ❤️ 1
    我用的是 phpdocumentor 的 reflection-docblock 包
    如果你没法用 composer 的话可以看看它的实现参考一下
    wesley
        3
    wesley  
       Apr 11, 2016   ❤️ 1
    反射 + 正则
    vus520
        4
    vus520  
       Apr 11, 2016   ❤️ 1
    还有个办法,不需要依赖,自己 parse

    $class = new \ReflectionClass($class);
    $methods = $class->getMethods();

    获取每个 method 的注释,再正则取
    $method->getDocComment();
    zonghua
        5
    zonghua  
       Apr 12, 2016 via iPhone   ❤️ 1
    这样就能创造 PHP 的装饰器 yu   fu
    Kokororin
        6
    Kokororin  
       Apr 12, 2016   ❤️ 1
    zeevin
        8
    zeevin  
       Apr 21, 2016
    function getDocComment($str, $tag = '')
    {
    if (empty($tag))
    {
    return $str;
    }

    $matches = array();
    preg_match("/".$tag."(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);

    if (isset($matches[1]))
    {
    return trim($matches[1]);
    }

    return '';
    }

    $falg = getDocComment($doc, '@flag');
    zeevin
        9
    zeevin  
       Apr 21, 2016
    以上方法和 @vus520 方法联合使用
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5624 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 06:48 · PVG 14:48 · LAX 23:48 · JFK 02:48
    ♥ Do have faith in what you're doing.