PHP Reflection mechanism usage example, php Reflection instance. PHP Reflection mechanism usage example. php Reflection instance this article describes the PHP Reflection mechanism usage and shares it with you for your reference. The specific method is as follows: the sample code is as follows: PHP Reflection mechanism usage example, php Reflection instance
The example in this article describes the usage of the PHP Reflection mechanism and shares it with you for your reference. The specific method is as follows:
The demo code is as follows:
<?phpclass 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 ClassOneDelegator class is used to replace the ClassOne class to implement its method.
Similarly, the following code can be run:
<?phpclass 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 help you with PHP programming.
What is PHP Reflection mechanism?
It can also be called ING. To put it bluntly, he can not only clone objects, but also call object variables
The method is quite powerful. Php API5 has an explanation of the object and has the opportunity to read it, similar
In java. Of course, this feature is enough to prove that php and asp are quite different!
The principle of the JAVA reflection mechanism is that it is best to include an example of how to use the reflection mechanism.
Field [] fields = object. getClass (). getDeclaredFields ();
For (int j = 0; j <fields. length; j ++ ){
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 ();
}
}
Examples in this article describe the usage of PHP Reflection mechanism and share it with you for your reference. The specific method is as follows: the sample code is as follows...