head-img Force's Blog

PHP利用反射获取方法(函数)注释

PHP

问题描述

今天写后台菜单管理,需要用程序读取某个方法的注释描述。如下,想获取Desc后面的文字。

/**
 * Func: func_comment
 * User: Force
 * Date: 2021/9/25
 * Time: 15:50
 * Desc: 注释描述test
 */

函数

第一个参数:object Or Method
第二个参数:方法名
第三个参数:注释名

function func_comment($module, $fc, $line_name) {

    if(empty($module) || empty($fc) || empty($line_name)) {
        return false;
    }

    $act = new $module();
    $func = new ReflectionMethod($act, $fc);
    $tmp = $func->getDocComment();

    preg_match_all('/' . $line_name . ':(.*?)\n/',$tmp,$tmp);

    $tmp = trim($tmp[1][0]);
    $tmp = $tmp != '' ? $tmp : '无';

    return $tmp;
}

调用处

$class = "\\admin\\controller\\{$controller}";
$comment = func_comment($class, $func['name'], 'Desc');

结果$comment输出 注释描述test

本文参考自:http://www.chenglin.name/php/blog/318.html

点我评论
打赏本文
二维码


124

文章

14

标签

 访客统计  Update-******