The examples in this article describe the use of PHP reflection mechanism and are shared with you for your reference. The specific method is as follows:
The demonstration sample 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 his method is implemented through the proxy class ClassOneDelegator instead of the ClassOne class.
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(); ?>
I hope this article will be helpful to everyone’s PHP programming design.
For more articles related to PHP reflection mechanism usage examples, please pay attention to the PHP Chinese website!