PHP 反射机制实现动态代理的代码
程序员文章站
2022-03-08 13:55:39
演示用代码如下所示: 复制代码 代码如下:
演示用代码如下所示:
<?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 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
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 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();
?>