Home  >  Article  >  Backend Development  >  Detailed explanation of how to implement PHP reflection mechanism code

Detailed explanation of how to implement PHP reflection mechanism code

伊谢尔伦
伊谢尔伦Original
2017-06-30 10:32:56934browse

Through proxy classClassOneDelegator instead of ClassOne class to implement his method.

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 his method.
Similarly, the following code can also be run:

<?php 
class ClassOne { 
function callClassOne() { 
print "In Class One"; 
} 
} 
class ClassOneDelegator { 
private $targets; 
function add
Object
($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(); 
?>


The above is the detailed content of Detailed explanation of how to implement PHP reflection mechanism code. For more information, please follow other related articles on 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