演示用代码如下所示:
<?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类来实现他的方法。
同样的,如下的代码也是能够运行的:
<?php class ClassOne { function callClassOne() { print "In Class One"; } } class ClassOneDelegator { private $targets; function add Object ($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反射机制代码详解的详细内容,更多请关注二当家的素材网其它相关文章!
友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群