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

【PHP高级特性】Reflection

时间:2023-03-29 23:31:27 PHP

PHP5开始提供完整的反射API。有反射类(ReflectionClass)和反射函数(ReflectionFunction)等,功能大同小异,这里主要以ReflectionClass为栏目进行讲解。什么是反射?他指的是在PHP的运行状态下,动态获取对象的类、方法、属性、参数、注释等信息,动态调用对象方法的功能。什么可以帮助我们构建复杂的、可扩展的应用程序。比如自动加载插件、自动生成文档等代码示例。本例为通用API入口HttpApi.phpnamespacetwinkle\service\http;classHttpApi{private$class;公共函数__construct($class){$this->class=$class;}publicfunctionparseRequest($method,$params=[]){$class=new\ReflectionClass($this->class);$instance=$class->newInstanceArgs($params);$method=$class->getMethod($method);$参数=[];foreach($method->getParameters()as$param){$name=$param->getName();}如果(isset($params[$name])){$args[$name]=$params[$name];}else{try{$args[$name]=$param->getDefaultValue();}catch(\Exception$e){thrownewRequestException('请求参数失败',500);}}}返回[$实例,$方法,$参数];}}NotFoundService.phpnamespaceapp\services;useapp\base\Service;classNotFoundServiceextendsService{publicfunctionerror(){return$this->format(['status'=>1,'msg'=>'请不要合法,请确认服务和方法不存在']);}}使用范例$params=$_REQUEST;$serviceName=isset($params['service'])?$params['service']:'NotFound';$methodName=isset($params['method'])?$params['method']:'error';$class='\\app\\services\\'。海峡::ucWords($服务名称)。'服务';list($instance,$method,$args)=(newHttpApi($class))->parseRequest($methodName,$params);echojson_encode(($method->invokeArgs($instance,$args)));