PHP Reflection Mechanism Usage example, PHP reflection instance
In this paper, the use of the reflection mechanism of PHP is described and shared for everyone's reference. Here's how:
The demo sample code looks like this:
<?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 proxy class Classonedelegator instead of the Classone class to implement his method.
Similarly, the following code is also capable of running:
<?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 is helpful to everyone's PHP programming.
What is the reflection mechanism of PHP
can also be called mappings. To be straightforward, not only can he clone objects, but the variables that can invoke the object are very
To the method, quite powerful. PHP API5 with an explanation of the object, there is a chance to look down, similar to
In Java. Of course, this feature is enough to prove that PHP and ASP still have a very big difference!
The principle of the reflection mechanism of Java is that it is best to take an example of how to use the reflection mechanism
field[] fields = Object.getclass (). Getdeclaredfields ();
for (int j = 0; J < Fields.length; J + +) {
try {
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 www.bkjia.com true http://www.bkjia.com/PHPjc/871097.html techarticle PHP Reflection mechanism usages, examples of PHP reflection examples of the use of the PHP reflection mechanism, shared for everyone for reference. Here's how: the Demo sample code is as follows ...