doufan1899 2011-05-01 13:45 采纳率: 100%
浏览 44
已采纳

将请求重定向到另一个类

I have three classes. Class A, Class B, Class C. What I am trying to do, send a request to Class B form Class A, and Class B must redirect that request to Class c.

May be a simple example from below will give a certain idea.

class classa {
    public function __construct() {
        $obj_classb = new classb;
        $obj_classb -> someRequest(); // This request must go to Class B and query the Class C        
    }
}

class classb {
    //This class must do something, which is going to redirect any sorts of request it receives to the next classc
}

class classc {
    public function someRequest() {
        //do whatever
    }
}

Any Idea?

  • 写回答

1条回答 默认 最新

  • dongqiuxu2270 2011-05-01 13:59
    关注

    You can create a "redirector" class by overriding the __call method like this:

    class classb {
        private $obj_classc;
    
        public function __construct() {
            $this->obj_classc = new classc;
        }
    
        public function __call($name, $arguments) {
            return call_user_func_array(array($this->obj_classc, $name), $arguments);
        }
    }
    

    Of course this will "forward" only method calls; if you are interested in forwarding property getters/setters etc you will have to override more magic methods.

    Choosing the forwarding target can also be arranged (in this example it's just an automatically-created classc object; but you can pass it as a parameter in the constructor or provide it in any other way you choose).

    Update: Magic functions you need to override to forward property accesses:

    public function __set($name, $value) {
        $this->obj_classc->$name = $value;
    }
    
    public function __get($name) {
        return $this->obj_classc->$name;
    }
    
    public function __isset($name) {
        return isset($this->obj_classc->$name);
    }
    
    public function __unset($name) {
        unset($this->obj_classc->$name);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line