Overriding: PHP OOP

Video tutorial to illustrate Overriding in Object Oriented PHP Programming.

Here, we take two class: A and B. Extend class A to class B. Then, define method display() in class A.

Overriding is an object-oriented programming feature that enables a child class to provide different implementation for a method that is already defined and/or implemented in its parent class or one of its parent classes. The overriden method in the child class should have the same name, signature, and parameters as the one in its parent class.

Class B extends Class A

< ?php
  class A
  {
   function display()
   {
    echo "Inside Class A";
   } 
  }
  
  class B extends A
  {
   
  }
  
  $obj = new B();
  $obj->display();
?>

Next, redefine the same method display() inside class B too, with a different output.

Redefine method display inside class B

< ?php
  class A
  {
   function display()
   {
    echo "Inside Class A";
   } 
  }
  
  class B extends A
  {
   function display()
   {
    echo "Inside Class B";
   } 
  }
  
  $obj = new B();
  $obj->display();
?>

Now, the method inside class B has higher precedence over it’s parent class method.

Invoking parent method using Scope Resolution Operator

< ?php
  class A
  {
   function display()
   {
    echo "Inside Class A";
   } 
  }
  
  class B extends A
  {
   function display()
   {
         parent::display();
   }   
  }
  
  $obj = new B();
  $obj->display();
?>

You can invoke parent method from subclass by using the keyword parent followed by scope resolution operator and the method name.

Overriding: PHP OOP



YouTube Link: https://www.youtube.com/watch?v=5tcIUn6nbVE [Watch the Video In Full Screen.]



Note:
1. Altering of function definition in the derived class does not alter the function definition in the parent class.
2. You can override both attributes and methods in the subclass.