PHP reflection mechanism code to implement dynamic proxy_PHP tutorial

WBOY
Release: 2016-07-13 17:35:31
Original
788 people have browsed it

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-...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!