Home  >  Article  >  Backend Development  >  PHP reflection mechanism code to implement dynamic proxy_PHP tutorial

PHP reflection mechanism code to implement dynamic proxy_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:35:31783browse

The demo code is as follows:

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


Output result:
In Class One
It can be seen that its method is implemented through the proxy class ClassOneDelegator instead of the ClassOne class.
Similarly, the following code can also be run:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508326.htmlTechArticleThe demonstration code is as follows: ?php class ClassOne { function callClassOne() { print "In Class One"; } } class ClassOneDelegator { private $targets; function __construct() { $this-...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn