您好,登录后才能下订单哦!
密码登录
            
            
            
            
        登录注册
            
            
            
        点击 登录注册 即表示同意《亿速云用户服务条款》
        反射 Reflection
反射可以简单理解为扫描类的属性、方法和注释的能力。
用法
PHP 为我们提供了丰富的方法,使我们可以方便的使用。
$reflect = new ReflectionClass('App\Foo');
$reflect->getMethods(); // 获取方法的数组
$reflect->getDocComment(); // 获取文档注释
……应用
有时系统需要向用户提供内置方法文档说明来使用,那么我们则可以通过 PHP 反射实现。
创建内置函数类
class FooFunction{
    /**
     * 获取当前周周一时间戳
     *
     * @return false|string
     */
    public static function mondayTimeStamp(){
        $targetTime = strtotime('now');
        $w = date('w', $targetTime);
        $w = ($w == 0 ? 7 : $w);
        return mktime(0,0,0, date('m', $targetTime), date('d', $targetTime)-($w-1), date('Y', $targetTime));
    }
    /**
     * 获取当前周周一日期
     *
     * @return false|string
     */
    public static function mondayDate(){
        return date('Y-m-d', self::mondayTimeStamp());
    }
}扫描内置函数类,生成文档
// 利用 PHP 反射
$reflect = new ReflectionClass('FooFunction');
$data = [];
// 获取类中的方法
$methods = $reflect->getMethods();
foreach ($methods as $method){
    $methodName = $method->getName();
    $methodDocStr = $reflect->getMethod($methodName)->getDocComment();
    // 过滤方法注释前面的(*)
    $pattern = "/[@a-zA-Z\\x{4e00}-\\x{9fa5}]+.*/u";
    preg_match_all($pattern, $methodDocStr, $matches, PREG_PATTERN_ORDER);
    $data[] = [
        'name' => $methodName,
        'doc' => $matches[0]
    ];
}
echo json_encode($data);结果
[
    {
        "name": "mondayTimeStamp",
        "doc": [
            "返回当前周周一时间戳",
            "@return false|string"
        ]
    },
    {
        "name": "mondayDate",
        "doc": [
            "返回当前周周一日期",
            "@return false|string"
        ]
    }
]以上就是使用PHP反射机制获取函数文档的详细内容,更多请关注亿速云其它相关文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。