PHP

Inheritance in PHP

In this article, I will explain the Inheritance in PHP.

The objects relate to each other in many ways. For instance, an object may be a special kind of another object. In other words, the object is the special case of some generalized object. For example, a Course object can have attributes like course title, duration, and credits. While the objects like Short Term Course and Vocational Course are the special cases of the Course. In this example, a Generalization-Specialization relationship exists between objects. Another example is the Person object which is a general object. While the objects like Student, Employee, Customer, Faculty, User are the special cases of the object Person.

Understanding Inheritance

Basically, inheritance refers to a concept in object-oriented programming which represents the IS-A relationship among objects. For instance Customer IS-A Person. Therefore inheritance specifies that there is a parent class and a child class that inherits the properties of the parent class. Therefore, inheritance allows us to create a subclass of a given class. In other words, we can derive a subclass from an existing class. Further, we can add unique attributes to the newly derived class. In such a case, the existing class is called a superclass, base class, or the parent class. Whereas the new class is known as subclass or child class or derived class.

Implementing Inheritance in PHP

In order to inherit a class in PHP, we use the extends keyword. The following code shows the syntax of inheriting a class.

class <baseclass name>
{
     // properties and methods
}
class <derived class name> extends <base class name>
{
    // properties and methods
}

Also, if want that certain properties of the base class should be available in the derived class, we need to use the protected access modifier. The following code shows an example of inheritance and the use of a protected access modifier.

<?php
 class A
 {
    protected $x, $y;
    function __construct($x, $y)
    {
      echo 'Inside Base Class Constructor...<br>';
      $this->x=$x;
      $this->y=$y;
    }
    function sum()
    {
	echo '<br>Sum = ',$this->x+$this->y;
    }
 }

 class B extends A
 {
      public $z;
      function __construct($p, $q, $r)
      {
	      echo 'Inside Derived Class Constructor...<br>';	
	      parent::__construct($p, $q);
              $this->z=$r;
      }
      function SumOfThree()
      {
	echo '<br>Sum of Three = ',$this->x+$this->y+$this->z;
      }
         
 }
 $ob=new B(1,2,3);
 $ob->sum();
 $ob->SumOfThree();
?>
Example of Inheritance in PHP
Example of Inheritance in PHP

http://www.programmingempire.com/example-of-inheriting-a-class-in-php/


Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

You may also like...