php怎麼取得方法的註釋

藏色散人
發布: 2023-03-08 16:20:02
原創
3475 人瀏覽過

php取得方法的註解:先開啟對應的PHP檔案;然後透過php中的反射機制,取得該類別的文件註解;最後透過取得其所有的方法,取得方法的註解即可。

php怎麼取得方法的註釋

本文操作環境:windows7系統、PHP7.1版,DELL G3電腦

php反射取得類別與方法中的註釋

透過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__).&#39;function.php&#39;;
require_once dir(__DIR__).&#39;TestClass.php&#39;;
 
$class_name = &#39;TestClass&#39;;
 
$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(
        &#39;class_name&#39;=>$class_name,
        &#39;method_name&#39;=>$method->getName(),
        &#39;arguments&#39;=>$arguments,
        &#39;defaults&#39;=>$defaults,
        &#39;metadata&#39;=>$metadata,
        &#39;method_flag&#39;=>$method_flag
    );
    print_r($call);
    echo "\r\n-----------------------------------\r\n";
}
登入後複製

function.php【推薦學習:《PHP影片教學》】

<?php
require_once dir(__DIR__).&#39;DocParser.php&#39;;
 
/**
 * 解析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 = &#39;0000-00-00&#39;) {
        echo "public";
    }
    /**
     * @desc 获取private方法
     *
     * @url GET private_test
     * @return int id
     */
    private function getPrivateMethod($no_default,$time = &#39;0000-00-00&#39;) {
        echo "private";
    }
 
    /**
     * @desc 获取protected方法
     *
     * @url GET protected_test
     * @param $no_defalut,$time
     * @return int id
     */
    protected function getProtectedMethod($no_default,$time = &#39;0000-00-00&#39;) {
        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 = &#39;&#39;) {
        if ($doc == &#39;&#39;) {
            return $this->params;
        }
        // Get the comment
        if (preg_match ( &#39;#^/\*\*(.*)\*/#s&#39;, $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 ( &#39;#^\s*\*(.*)#m&#39;, $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 [&#39;description&#39;] )) {
                if (isset ( $desc )) {
                    // Store the first line in the short description
                    $this->params [&#39;description&#39;] = implode ( PHP_EOL, $desc );
                }
                $desc = array ();
            } elseif ($parsedLine !== false) {
                $desc [] = $parsedLine; // Store the line in the long description
            }
        }
        $desc = implode ( &#39; &#39;, $desc );
        if (! empty ( $desc ))
            $this->params [&#39;long_description&#39;] = $desc;
    }
    private function parseLine($line) {
        // trim the whitespace from the line
        $line = trim ( $line );
        
        if (empty ( $line ))
            return false; // Empty line
        
        if (strpos ( $line, &#39;@&#39; ) === 0) {
            if (strpos ( $line, &#39; &#39; ) > 0) {
                // Get the parameter name
                $param = substr ( $line, 1, strpos ( $line, &#39; &#39; ) - 1 );
                $value = substr ( $line, strlen ( $param ) + 2 ); // Get the value
            } else {
                $param = substr ( $line, 1 );
                $value = &#39;&#39;;
            }
            // 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 == &#39;param&#39; || $param == &#39;return&#39;)
            $value = $this->formatParamOrReturn ( $value );
        if ($param == &#39;class&#39;)
            list ( $param, $value ) = $this->formatClass ( $value );
        
        if (empty ( $this->params [$param] )) {
            $this->params [$param] = $value;
        } else if ($param == &#39;param&#39;) {
            $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 ( &#39;,&#39;, $val );
                if (count ( $val ) > 1)
                    $value [$key] = $val;
            }
        } else {
            $param = &#39;Unknown&#39;;
        }
        return array (
                $param,
                $value 
        );
    }
    private function formatParamOrReturn($string) {
        $pos = strpos ( $string, &#39; &#39; );
        
        $type = substr ( $string, 0, $pos );
        return &#39;(&#39; . $type . &#39;)&#39; . substr ( $string, $pos + 1 );
    }
}
登入後複製

以上是php怎麼取得方法的註釋的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!