php获取方法的注释:首先打开相应的php文件;然后通过php中的反射机制,获取该类的文档注释;最后通过获取其所有的方法,获取方法的注释即可。
本文操作环境:windows7系统、php7.1版,dell g3电脑
php反射获取类和方法中的注释
通过php中的反射机制,获取该类的文档注释,再通过获取其所有的方法,获取方法的注释
所用到的主要类及其方法
reflectionclassreflectionclass::getdoccommentreflectionclass::getmethods $method->getname()$method->getdoccomment();$method->isprotected();$method->getparameters(); $param->getname();$param->isdefaultvalueavailable();$param->getdefaultvalue()
测试类如下:
test.php
<?phpheader("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"; //获取类中的方法,设置获取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(        '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【推荐学习:《php视频教程》】
<?phprequire_once dir(__dir__).'docparser.php'; /** * 解析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 = '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  该类源自一个开源项目
<?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怎么获取方法的注释的详细内容。
   
 
   