PHP反射機制

反射

  1. ReflectionClass

    1. 獲取被包裝類的實例化對象
      ReflectionClass::newInstance()
    2. 獲取改類的屬性
      ReflectionClass::getproperties()
    3. 獲取註釋:
      foreach (propertiesas property) {
      if (property->isProtected()) { docblock = $property->getDocComment();
    4. 獲取類的方法

      getMethods() 來獲取到類的所有methods。

      hasMethod(string) 是否存在某個方法

      getMethod(string) 獲取方法

    5. 執行類的方法

          $instance  =  ReflectionClass::newInstance();
      $instance->fun1();
      
      $method = $class->getmethod('getName'); // 獲取Person 類中的getName方法
      $method->invoke($instance);    // 執行getName 方法
      
  2. ReflectionMethod

    1. 是否“public”、“protected”、“private” 、“static”類型
    2. 方法的參數列表
    3. 方法的參數個數
    4. 反調用類的方法
      • 最簡單的應用:
class test{
    public function fun1($a,$b){
        echo '$a is :'.$a.', $b is :'.$b."<br>";
    }
}
$obj = new test;
$r = new ReflectionClass($obj);
//ReflectionClass的構造參數既可以是一個包含類名的字符串(string)也可以是一個對象(object)。


$method = $r->getMethod('fun1');
$method->invoke($obj,1,333);
//$method->invokeArgs($obj,[1,333]);
  • 用法實例
<?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();
?>

可見,通過代理類ClassOneDelegator來代替ClassOne類來實現他的方法。

<?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();
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章