php獲取方法的注釋

小編給大家分享一下php獲取方法的注釋,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供新和網(wǎng)站建設(shè)、新和做網(wǎng)站、新和網(wǎng)站設(shè)計(jì)、新和網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、新和企業(yè)網(wǎng)站模板建站服務(wù),10多年新和做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。

php獲取方法的注釋:首先打開相應(yīng)的PHP文件;然后通過php中的反射機(jī)制,獲取該類的文檔注釋;最后通過獲取其所有的方法,獲取方法的注釋即可。

php反射獲取類和方法中的注釋

通過php中的反射機(jī)制,獲取該類的文檔注釋,再通過獲取其所有的方法,獲取方法的注釋

所用到的主要類及其方法

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__).'function.php';
require_once dir(__DIR__).'TestClass.php';
 
$class_name = 'TestClass';
 
$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";
 
//獲取類中的方法,設(shè)置獲取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類型的
    //獲取方法的參數(shù)
    $params = $method->getParameters();
    $position=0;    //記錄參數(shù)的次序
    foreach ($params as $param){
        $arguments[$param->getName()] = $position;
        //參數(shù)是否設(shè)置了默認(rèn)參數(shù),如果設(shè)置了,則獲取其默認(rèn)值
        $defaults[$position] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : NULL;
        $position++;
    }
 
    $call = array(
        'class_name'=>$class_name,
        'method_name'=>$method->getName(),
        'arguments'=>$arguments,
        'defaults'=>$defaults,
        'metadata'=>$metadata,
        'method_flag'=>$method_flag
    );
    print_r($call);
    echo "\r\n-----------------------------------\r\n";
}

function.php【推薦學(xué)習(xí):《PHP視頻教程》】

<?php
require_once dir(__DIR__).'DocParser.php';
 
/**
 * 解析doc
 * 下面的DocParserFactory是對其的進(jìn)一步封裝,每次解析時,可以減少初始化DocParser的次數(shù)
 *
 * @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 = '0000-00-00') {
        echo "public";
    }
    /**
     * @desc 獲取private方法
     *
     * @url GET private_test
     * @return int id
     */
    private function getPrivateMethod($no_default,$time = '0000-00-00') {
        echo "private";
    }
 
    /**
     * @desc 獲取protected方法
     *
     * @url GET protected_test
     * @param $no_defalut,$time
     * @return int id
     */
    protected function getProtectedMethod($no_default,$time = '0000-00-00') {
        echo "protected";
    }
}

DocParser.php  該類源自一個開源項(xiàng)目

<?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 = '') {
        if ($doc == '') {
            return $this->params;
        }
        // Get the comment
        if (preg_match ( '#^/\*\*(.*)\*/#s', $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 ( '#^\s*\*(.*)#m', $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 ['description'] )) {
                if (isset ( $desc )) {
                    // Store the first line in the short description
                    $this->params ['description'] = implode ( PHP_EOL, $desc );
                }
                $desc = array ();
            } elseif ($parsedLine !== false) {
                $desc [] = $parsedLine; // Store the line in the long description
            }
        }
        $desc = implode ( ' ', $desc );
        if (! empty ( $desc ))
            $this->params ['long_description'] = $desc;
    }
    private function parseLine($line) {
        // trim the whitespace from the line
        $line = trim ( $line );
        
        if (empty ( $line ))
            return false; // Empty line
        
        if (strpos ( $line, '@' ) === 0) {
            if (strpos ( $line, ' ' ) > 0) {
                // Get the parameter name
                $param = substr ( $line, 1, strpos ( $line, ' ' ) - 1 );
                $value = substr ( $line, strlen ( $param ) + 2 ); // Get the value
            } else {
                $param = substr ( $line, 1 );
                $value = '';
            }
            // 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 == 'param' || $param == 'return')
            $value = $this->formatParamOrReturn ( $value );
        if ($param == 'class')
            list ( $param, $value ) = $this->formatClass ( $value );
        
        if (empty ( $this->params [$param] )) {
            $this->params [$param] = $value;
        } else if ($param == 'param') {
            $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 ( ',', $val );
                if (count ( $val ) > 1)
                    $value [$key] = $val;
            }
        } else {
            $param = 'Unknown';
        }
        return array (
                $param,
                $value 
        );
    }
    private function formatParamOrReturn($string) {
        $pos = strpos ( $string, ' ' );
        
        $type = substr ( $string, 0, $pos );
        return '(' . $type . ')' . substr ( $string, $pos + 1 );
    }
}

以上是“php獲取方法的注釋”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

本文標(biāo)題:php獲取方法的注釋
文章轉(zhuǎn)載:http://muchs.cn/article44/iidshe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、網(wǎng)站建設(shè)、電子商務(wù)、自適應(yīng)網(wǎng)站、App開發(fā)營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化