PHP反射机制实现动态代理的代码

来源:互联网 发布:pdf免费编辑软件 编辑:程序博客网 时间:2024/06/05 09:01
 演示用代码如下所示:<?phpclass 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类来实现他的方法。同样的,如下的代码也是能够运行的:<?phpclass 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();?>
http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2008/1216/139.html

0 0
原创粉丝点击