duanji7881 2014-11-18 16:28
浏览 63
已采纳

PHP OOP - 如何调用子类的重写方法

Consider class A and B as follows:

Class A {

   public function A1 (){
      $this->A2();
   }

   public function A2 (){}

}

Class B extends A {

  public function A2 () {} // overriding A2

}


$instance= new B ();
$instance -> A1();  // Calling A1 of class B which calls the parent class A1 actually

As you can see Class B overrides function A2. A2 is called from class A method A1

The problem is that it calls the A2 in class A and not the overriding A2 in class B.

How can I make sure that if I override a method, the overriding method will be invoked even if it is called from a parent class (A) method (when the actual object is an instance of the overriding (B) class.

  • 写回答

1条回答 默认 最新

  • douxianji6104 2014-11-18 16:39
    关注

    I am knowing this is not an answer, but i want to make clear, what OP asking, and want to formatting the code.

    Class A {
    
        public function A1() {
            echo "Class A, method A1 <br />";
            $this->A2();
        }
    
        public function A2() {
            echo "Class A, method A2 <br />";
        }
    
    }
    
    Class B extends A {
    
        public function A2() {
            echo "Class B, method A2 <br />";
        }
    
        // overriding A2
    }
    
    $instance = new B ();
    $instance->A1();  
    

    Output of this is:

    Class A, method A1
    Class B, method A2 
    

    To OP: What is your desired output?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器