获取PHP文档注释的内容

前几天做项目,需要记录操作日志,用tp框架写。每次根据操作单独写日志的内容太麻烦了,所以想到将需要记录的方法日志记录到每个方法的注释上,这样随时灵活更改。所以,查了一些资料,最终总结如下:

if (!function_exists("getMethodAnnotationValue")){
    /**
     * @param $className 类全名 xxx:class
     * @param $methodName 方法名 action
     * @param $annotationName 注释名称 desc
     * @return mixed|null
     * @throws ReflectionException
     * @author: 大炸蟹
     * @createTime: 2024/8/14
     */
    function getMethodAnnotationValues($className, $methodName, $annotationName="@log") {
        $reflectionMethod = new ReflectionMethod($className, $methodName);
        $docComment = $reflectionMethod->getDocComment();
        // 将所有多个空格转为一个
        $docComment=preg_replace("/\s+/",' ',$docComment);
        $comment_arr = explode("* ", $docComment);

        $comment_arr_withkeyval = [];
        foreach ($comment_arr as $item) {
            $item=str_replace(['/*','*/'],'',$item);
            $item=trim($item);
            if (empty($item)) continue;
            
            if (str_contains($item," ")){
                $item_arr = explode(" ", $item);
                $key = trim($item_arr[0],"@");
                $val = trim($item_arr[1]);
                if (!empty($val)) $comment_arr_withkeyval[$key] = $val;
            }else{
                $comment_arr_withkeyval[]=$item;
            }
        }
        if (!empty($annotationName)) return $comment_arr_withkeyval[$annotationName];
        return $comment_arr_withkeyval;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值