PHP 反射之动态代理

反射可以探知类的内部结构 可以用它做hook实现插件功能,或者做动态代理

与反射相关

  • 类和对象相关的函数
    get_object_vars
    get_class_methods
    get_class_vars
    get_class
    get_parent_class
    method_exists
    property_exists
    trait_exists
  • 反射相关的 API 类
    reflectiontype
    reflectionproperty
    reflectionobject
    reflectionfunction
    reflectionmethod
    reflectionexception
    reflectionextension
    reflectionparameter
    reflectionfunctionabstract
    reflectiongenerator
    reflectionclass
    reflectionclassconstant
    reflectionzendextension

    反射API功能更强大,甚至能还原这个类的原型,包括方法的访问权限等

应用场景

一个是对对象进行调试,另一个是获取类的信息,通常有以下应用方式

  • 文档生成 用它对文件里的类进行扫描,生成描述文档
  • 插件开发 在MVC和插件开发中,常见使用反射

缺点

  • 反射的性能消耗也很大,一般情况下尽量不使用
  • 会破坏类的封装性,因为反射可以使本不应该暴露的方法或属性被强制暴露了出来

实例

下面是一个利用反射特性,实现的简单的数据库动态代理

基于动态代理,可以有更多的想象空间,如实现拦截器,属性方法增加,裁剪等等

class Mysql
{
    function connect($db){
         echo "connecting database ${db[0]}\r\n";
    }
}
class SqlProxy
{
    private $target;
     function __construct($tar){
         $this->target[]  = new $tar();
     }

     function __call($name, $args){
         foreach($this->target as $obj){
           $r = new ReflectionClass($obj);
             if($method = $r->getMethod($name)){
                 if($method->isPublic() && !$method->isAbstract()){
                     echo "method before record \r\n";
                     $method->invoke($obj,$args);
                     echo "method after record\r\n";
                 }
             }
         }
     }
 }
 $obj = new SqlProxy('Mysql');
 $obj->connect('member');

其它

  • echoprint 都是语言结构,但是后者有返回值
  • print_rvar_dump 是普通函数 皆可打印多种类型数据,但后者会输出数据类型,前者第二参数可改变输出为返回
本作品采用《CC 协议》,转载必须注明作者和本文链接
pardon110
讨论数量: 1

报错 $r未定义 if($method = $r->getMethod($name)){

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
开发者 @ 社科大
文章
134
粉丝
24
喜欢
101
收藏
55
排名:106
访问:8.9 万
私信
所有博文
社区赞助商