Usage Example of PHP Reflection Mechanism

  • 2021-07-16 02:03:27
  • OfStack

This article illustrates the usage of PHP reflection mechanism, and shares it with you for your reference. The specific methods are 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:

In Class One

It can be seen that the proxy class ClassOneDelegator is used instead of the ClassOne class to implement his method.

Similarly, the following code can also 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 is helpful to everyone's PHP programming.


Related articles: