您好,欢迎访问一九零五行业门户网

使用PHP反射机制获取函数文档

反射 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教程》
以上就是使用php反射机制获取函数文档的详细内容。
其它类似信息

推荐信息