| 订阅 | 在线投稿
分享
 
 
 

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

来源:互联网  宽屏版  评论
2008-12-18 07:52:27

演示用代码如下所示:

<?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类来实现他的方法。

同样的,如下的代码也是能够运行的:

<?php

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

?>

演示用代码如下所示: <?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类来实现他的方法。 同样的,如下的代码也是能够运行的: <?php 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(); ?>
󰈣󰈤
 
 
 
>>返回首页<<
 
 热帖排行
 
 
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
©2005- 王朝网络 版权所有