zoukankan      html  css  js  c++  java
  • PHP 反射机制实现动态代理的代码

    演示用代码如下所示:

    class ClassOne {
        function callClassOne() {
            print "In Class One";
        }
    }
    class ClassOneDelegator {
        private $targets;
        function __construct() {
            $this->target[] = new ClassOne();
        }
        function __call($name, $args) {
            foreach ($this->target as $obj) {
                $r = new ReflectionClass($obj);
                if ($method = $r->getMethod($name)) {
                    if ($method->isPublic() && !$method->isAbstract()) {
                        return $method->invoke($obj, $args);
                    }
                }
            }
        }
    }
    $obj = new ClassOneDelegator();
    $obj->callClassOne();
    

    输出结果:
    In Class One
    可见,通过代理类ClassOneDelegator来代替ClassOne类来实现他的方法
    同样的,如下的代码也是能够运行的:

    class ClassOne {
        function callClassOne() {
            print "In Class One";
        }
    }
    class ClassOneDelegator {
        private $targets;
        function addObject($obj) {
            $this->target[] = $obj;
        }
        function __call($name, $args) {
            foreach ($this->target as $obj) {
                $r = new ReflectionClass($obj);
                if ($method = $r->getMethod($name)) {
                    if ($method->isPublic() && !$method->isAbstract()) {
                        return $method->invoke($obj, $args);
                    }
                }
            }
        }
    }
    $obj = new ClassOneDelegator();
    $obj->addObject(new ClassOne());
    $obj->callClassOne();
    
  • 相关阅读:
    抽象类使用细节
    super关键字
    JDK,JRE,JVM三者之间的爱恨情仇
    LinkedHashSet
    HashSet扩容成红黑树机制
    Set之HashSet
    finally关键字
    Hashcode方法
    equals方法和==的区别
    LinkedList
  • 原文地址:https://www.cnblogs.com/myphoebe/p/1995476.html
Copyright © 2011-2022 走看看