PHP反射机制用法实例,php反射实例
本文实例讲述了PHP反射机制的用法,分享给大家供大家参考之用。具体方法如下:
演示示例代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?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();
?>
|
登录后复制
输出结果:
In Class One
可见,通过代理类ClassOneDelegator来代替ClassOne类来实现他的方法。
同样的,如下的代码也是能够运行的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?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();
?>
|
登录后复制
希望本文所述对大家的PHP程序设计有所帮助。
也可以叫映射。说直白点,他不仅能克隆到对象,而且可以调用对象的变量甚
至方法,挺强大的。php API5关于与对象有解释,有机会可以看下,类似于
java中的。当然,这种特性,足以证明php与asp还是有很大区别的!
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();
}
}
http://www.bkjia.com/PHPjc/871097.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/871097.htmlTechArticlePHP反射机制用法实例,php反射实例 本文实例讲述了PHP反射机制的用法,分享给大家供大家参考之用。具体方法如下: 演示示例代码如下所...