成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

PHP反射機制實現動態代理的代碼

瀏覽:3日期:2024-02-18 08:24:51

演示用代碼如下所示:

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

標簽: PHP