使用PHP反射机制获取函数文档-php教程

资源魔 40 0
反射 Reflection

反射能够简略了解为扫描类的属性、办法以及正文的才能。

用法

PHP 为咱们提供了丰厚的办法,使咱们能够不便的应用。

$reflect = new ReflectionClass('App\Foo');
$reflect->getMethods(); // 猎取办法的数组
$reflect->getDocCo妹妹ent(); // 猎取文档正文
……

使用

有时零碎需求向用户提供内置办法文档阐明来应用,那末咱们则能够经过 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)->getDocCo妹妹ent();
    // 过滤办法正文后面的(*)
    $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教程》

以上就是应用PHP反射机制猎取函数文档的具体内容,更多请存眷资源魔其它相干文章!

标签: php php开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!