当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP 反射机制实现动态代理的代码

PHP
用php42书写安全的脚本
php4新函数集锦
php分页显示详解
用PHP制作动态计数器
php中两个网页之间的变量传送
PHP中用Socket发送电子邮件
php中分页显示文章标题
PHP下对缓冲区的控制
PHP 序列化(serialize)格式详解
使用PHP连接LDAP服务器
用PHP编程防范XSS跨站脚本攻击
建一个XMLHttpRequest对象池
用perl来解析你的php文档
PHP 开发程序加速运行探索之慢代码优化方法
超越模板引擎
用PHP制作zip压缩程序
JSON:数据传递的另一种模式
MySQL to JSON
利用PHP实现一种轻量级的MVC结构(原创)
用PHP实现XML备份

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-08-14   浏览: 130 ::
收藏到网摘: n/a

演示用代码如下所示:

以下为引用的内容:

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();

?>