演示用代码如下所示:
<?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反射机制代码详解的详细内容。