Home >php教程 >php手册 >PHP反射机制用法实例,php反射实例

PHP反射机制用法实例,php反射实例

WBOY
WBOYOriginal
2016-06-13 09:26:17993browse

PHP反射机制用法实例,php反射实例

本文实例讲述了PHP反射机制的用法,分享给大家供大家参考之用。具体方法如下:

演示示例代码如下所示:

<&#63;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();
&#63;>

输出结果:

In Class One

可见,通过代理类ClassOneDelegator来代替ClassOne类来实现他的方法。

同样的,如下的代码也是能够运行的:

<&#63;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();
&#63;>

希望本文所述对大家的PHP程序设计有所帮助。

什是PHP的反射机制

也可以叫映射。说直白点,他不仅能克隆到对象,而且可以调用对象的变量甚

至方法,挺强大的。php API5关于与对象有解释,有机会可以看下,类似于

java中的。当然,这种特性,足以证明php与asp还是有很大区别的!
 

JAVA的反射机制的原理是什 最好还可以带上个怎使用反射机制的例子

Field[] fields = object.getClass().getDeclaredFields();
for (int j = 0; 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();
}
}
 

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