【问题标题】:How to read comment blocks in PHP?如何在 PHP 中读取注释块?
【发布时间】:2010-10-17 00:34:06
【问题描述】:

我正在做一些自制的自动化文档,因为我有一个布局不是很标准的代码库,我想知道最好的方法是读取 PHP 文件并获取注释块的内容.我能想到的唯一方法是打开文件并逐行读取,但我想也许有一些内置的魔法可以为我解析文档,类似于反射函数。

每个文件的基本布局是这样的:

<?php // $Id$
/**
 * Here is this script's documentation, with information in pseudo-javadoc
 * type tags and whatnot.
 *
 * @attr    something    some information about something
 * @attr    etc          etc etc
 */
 // rest of the code goes here.

请务必注意,这些文件中没有定义任何函数或类。 cmets 与整个脚本相关。

【问题讨论】:

标签: php reflection comments


【解决方案1】:

查看Tokenizer。

要获取名为 test.php 的文件中的所有 cmets,您可以这样做:

$tokens = token_get_all(file_get_contents("test.php"));
$comments = array();
foreach($tokens as $token) {
    if($token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
        $comments[] = $token[1];
    }
}
print_r($comments);

【讨论】:

    【解决方案2】:

    看看 PHP5 附带的Reflection API,更具体地说是getDocComment():

    PHP 5 带有完整的反射 API 增加了以下功能 逆向工程类,接口, 功能和方法以及 扩展名。此外, 反射 API 还提供了 检索函数的 doc cmets, 类和方法。

    此外,根据代码库的大小,您可以通过修改 cmets 以适应 phpDocumentor 语法来减少工作量,这似乎已经非常接近了。

    【讨论】:

    • 这确实是一个非常奇怪的布局,恐怕需要非常具体的输出。反射函数似乎只适用于函数、类、对象等,能不能传个文件来解析?
    • +1 phpDocumentor,特别是如果代码已经是它的格式化程序。
    猜你喜欢
    • 2014-07-11
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2018-11-29
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多