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?

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

报告相同问题?