Home  >  Article  >  Backend Development  >  PHP reflection mechanism usage example code

PHP reflection mechanism usage example code

怪我咯
怪我咯Original
2017-07-12 16:21:481093browse

This article mainly introduces the usage of PHP reflection mechanism, which is an important concept in PHP programming. Friends who need it can refer to it

The examples in this article describe the usage of PHP reflection mechanism and share it with everyone. For everyone’s 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

is visible, replaced by the proxy class ClassOneDelegator ClassOne class to implement his methods.

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();
?>

The above is the detailed content of PHP reflection mechanism usage example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn