当前位置: 首页 > 后端技术 > PHP

使用PHP反射实现内置函数文档

时间:2023-03-29 18:23:41 PHP

reflection反射可以简单理解为扫描一个类的属性、方法、注解的能力。使用PHP为我们提供了丰富的方法,方便我们使用。$reflect=newReflectionClass('App\Foo');$reflect->getMethods();//获取方法数组$reflect->getDocComment();//获取文档注释...有时候系统需要为用户提供内置的Method文档来使用,那么我们可以通过PHP反射来实现。创建一个内置函数类classFooFunction{/***获取本周星期一的时间戳**@returnfalse|string*/publicstaticfunctionmondayTimeStamp(){$targetTime=strtotime('now');$w=date('w',$targetTime);$w=($w==0?7:$w);返回mktime(0,0,0,date('m',$targetTime),date('d',$targetTime)-($w-1),date('Y',$targetTime));}/***获取本周的星期一日期**@returnfalse|string*/publicstaticfunctionmondayDate(){returndate('Y-m-d',self::mondayTimeStamp());}}扫描内置函数类生成文档//使用PHP反射$reflect=newReflectionClass('FooFunction');$data=[];//获取类中的方法$methods=$reflect->getMethods();foreach($methodsas$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);$数据[]=['name'=>$methodName,'doc'=>$matches[0]];}echojson_encode($data);Result[{"name":"mondayTimeStamp","doc":["返回星期一的时间戳当前周","@returnfalse|string"]},{"name":"mondayDate","doc":["返回当前周星期一的日期","@returnfalse|string"]}]参考https://www.php.net/manual/zh...