Inheritance is one of the basic concepts of object-oriented programing methodology. It allows a class to “inherit” the properties and methods of an existing class by extending it.

Unless the child class “overrides” the methods of the existing class, they will maintain their original functionality.

The relationship between these classes is called a parent-child relationship. The existing class is called “parent” whereas the class that “inherit” all of the public and protected properties and methods from the parent class is called “child”.

Note: Properties and Methods that are set as private are not inherited.

Inheritance in PHP

Let’s create a simple class “Foo”.

class Foo{
  public $str ="PHP is awesome";
  public function display(){
    echo $this->str;
  }
}

The class “Foo” has a public property and a method.

$foo = new Foo();
$foo -> display();

This will display the string “PHP is awesome”.

Now, create a child class that inherits Foo’s properties and methods.

class Bar extends Foo{

// don’t have its own properties or methods yet. 

}

As you can see, it has no property or method of its own.

Let’s initialize an object of Bar.

$bar = new Bar();

To call the display method of the parent class, simply use the following piece of code.

$bar -> display();

This will call the parent’s display method.

Let’s override this method in the child class Bar now.

class Bar extends Foo
{
  public function display()
  {
    echo "This is child class";
  }
}
$bar = new Bar();
$bar -> display();

This will print “This is child class” string now.

One parent class can have multiple child classes.

Multi-Level Inheritance in PHP

PHP also supports multi-level inheritance.

<?php

class A {
        public function displayA(){
          echo "Hi, this is A";
        }
}

class B extends A {
  public function displayB(){
    echo "Hi, this is B, child of A";
  }
}

class C extends B {
  public function displayC(){
    echo "Hi, this is C, child of B";
  }
}


$a = new A();
$b = new B();
$c = new C();
$c -> displayA();

?>

This will print “Hi, this is A”.
Simple, right?

Final Keyword

When you want to prevent a child class to override a method from the parent class, use the final keyword.

<?php 

class A {
      final function dontOverride(){
        echo "this is reserved";
      }
        public function displayA(){
          echo "Hi, this is A";
        }
}

class B extends A {
  public function displayB(){
    echo "Hi, this is B, child of A";
  }
}

class C extends B {
  public function displayC(){
    echo "Hi, this is C, child of B";
  }
  public function dontOverride(){
    echo "this is reserved. So you can't use it here";
  }
}
?>

This will raise an error.

Now, you should be able to use inheritance with ease. In case, you have any questions, feel free to ask in the comment section.

Related Articles

 

 

 

Last modified: November 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.