Home > php教程 > php手册 > PHP中使用反射机制实现动态代理

PHP中使用反射机制实现动态代理

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-21 08:57:09
Original
1469 people have browsed it

演示用代码如下所示

classClassOne{
  functioncallClassOne(){
    print"InClassOne";
  }
}
classClassOneDelegator{
  private$targets;
  function__construct(){
    $this->target[]=newClassOne();
  }
  function__call($name,$args){
    foreach($this->targetas$obj){
      $r=newReflectionClass($obj);
      if($method=$r->getMethod($name)){
        if($method->isPublic()&&!$method->isAbstract()){
          return$method->invoke($obj,$args);
        }
      }
    }
  }
}
$obj=newClassOneDelegator();
$obj->callClassOne();
?>

  输出结果:

  In Class One

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

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

classClassOne{
  functioncallClassOne(){
    print"InClassOne";
  }
}
classClassOneDelegator{
  private$targets;
  functionaddObject($obj){
    $this->target[]=$obj;
  }
  function__call($name,$args){
    foreach($this->targetas$obj){
      $r=newReflectionClass($obj);
      if($method=$r->getMethod($name)){
        if($method->isPublic()&&!$method->isAbstract()){
          return$method->invoke($obj,$args);
        }
      }
    }
  }
}
$obj=newClassOneDelegator();
$obj->addObject(newClassOne());
$obj->callClassOne();
?>



Related labels:
php
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template