Home  >  Article  >  Backend Development  >  PHP reflection mechanism implements code for dynamic proxy

PHP reflection mechanism implements code for dynamic proxy

高洛峰
高洛峰Original
2016-12-23 12:55:311340browse

The demonstration code is as follows:

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

Output result:
In Class One
It can be seen that the proxy class ClassOneDelegator is used to replace the ClassOne class to implement its method.
Similarly, the following code can also be run:

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

For more code-related articles on the PHP reflection mechanism to implement dynamic proxy, please pay attention to the PHP Chinese website!

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