| 導購 | 订阅 | 在线投稿
分享
 
 
 

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(); ?>
󰈣󰈤
 
 
 
>>返回首頁<<
 
 
 
 
 熱帖排行
 
王朝網路微信公眾號
微信掃碼關註本站公眾號 wangchaonetcn
 
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有