Nir
Nir

Reputation: 25349

PHP OOP - how to call the overriding method of the child class

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.

Upvotes: 1

Views: 51

Answers (1)

vaso123
vaso123

Reputation: 12391

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?

Upvotes: 2

Related Questions