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

PHP反射ReflectionClass、ReflectionMethod在ThinkPHP框架的控制器调度模块中的应用

thinkphp框架的控制器模块是如何实现 前控制器、后控制器,及如何执行带参数的方法?
php系统自带的 reflectionclass、reflectionmethod 类,可以反射用户自定义类的中属性,方法的权限和参数等信息,通过这些信息可以准确的控制方法的执行。
reflectionclass:  [php手册]详情
主要用的方法:
hasmethod(string)  是否存在某个方法
getmethod(string)  获取方法
reflectionmethod:  [php手册]详情
主要方法:
ispublic()    是否为 public 方法
getnumberofparameters()  获取参数个数
getparamters()  获取参数信息
invoke( object $object [, mixed $parameter [, mixed $... ]] ) 执行方法  
invokeargs(object obj, array args)     带参数执行方法
实例演示:
ispublic()) { $class = new reflectionclass('blogaction'); // 执行前置方法 if ($class->hasmethod('_before_detail')) { $beforemethod = $class->getmethod('_before_detail'); if ($beforemethod->ispublic()) { $beforemethod->invoke($instance); } } $method->invoke(new blogaction); // 执行后置方法 if ($class->hasmethod('_after_detail')) { $beforemethod = $class->getmethod('_after_detail'); if ($beforemethod->ispublic()) { $beforemethod->invoke($instance); } }}// 执行带参数的方法$method = new reflectionmethod('blogaction', 'test');$params = $method->getparameters();foreach ($params as $param) { $paramname = $param->getname(); if (isset($_request[$paramname])) { $args[] = $_request[$paramname]; } elseif ($param->isdefaultvalueavailable()) { $args[] = $param->getdefaultvalue(); }}if (count($args) == $method->getnumberofparameters()) { $method->invokeargs($instance, $args);} else { echo 'parameters is wrong!';}

【另外一段参考代码】
ispublic()) { $class = new reflectionclass('blogaction'); // 执行前置方法 if ($class->hasmethod('_before_detail')) { $beforemethod = $class->getmethod('_before_detail'); if ($beforemethod->ispublic()) { $beforemethod->invoke($instance); } } $method->invoke(new blogaction); // 执行后置方法 if ($class->hasmethod('_after_detail')) { $beforemethod = $class->getmethod('_after_detail'); if ($beforemethod->ispublic()) { $beforemethod->invoke($instance); } }}// 执行带参数的方法$method = new reflectionmethod('blogaction', 'test');$params = $method->getparameters();foreach ($params as $param) { $paramname = $param->getname(); if (isset($_request[$paramname])) { $args[] = $_request[$paramname]; } elseif ($param->isdefaultvalueavailable()) { $args[] = $param->getdefaultvalue(); }}if (count($args) == $method->getnumberofparameters()) { $method->invokeargs($instance, $args);} else { echo 'parameters is wrong!';}

以上就介绍了php反射reflectionclass、reflectionmethod在thinkphp框架的控制器调度模块中的应用,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息