Home >Backend Development >PHP Tutorial >PHP reflection mechanism usage examples, php reflection examples_PHP tutorial
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 demo 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.
It can also be called mapping. To put it bluntly, it can not only clone objects, but also call variables and even methods of objects, which is quite powerful. PHP API5 has an explanation about objects. You can read it if you have a chance. It is similar to the one in
java. Of course, this feature is enough to prove that there is a big difference between php and asp!
try {
Method method = object.getClass( ).getMethod("get" + name.substring(0, 1).toUpperCase()
+ name.substring(1), new Class[] {});
Object result = method.invoke(object , new Object[] {});
} catch (Exception e) {
e.getStackTrace();
}
}
http://www.bkjia.com/PHPjc/871097.html