PHP Inheritance

Classes can inherit the properties and methods of another class. This process of extensibility is known as inheritance. It is probably the most powerful reason behind using the object-oriented programming model.

In inheritance a new class can be derived form an existing class, where the newly derived class is known as child or subclass and the existing class is known as parent or superclass. The sub-class has its own properties and functions which can be derived from the  superclass and added to that, the superclass can have its own properties.

In PHP the extends keyword is used to derive the new class form an existing class.  The syntax would be :
class child extends parent {
  // code goes here
}
Where the child is newly derived class (or subclass) and parent is superclass. Now lets see an example of it.

Example :
<?php

class Student {
  var $name;
  var $age;

  function setData($arg1, $arg2) {
    $this->name = $arg1;
    $this->age = $arg2;
  }

  function showData() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age . "<br/><br/>";
  }

}

class Details extends Student {
  var $address;

  function setAddress($arg) {
    $this->address = $arg;
  }

  function printInfo() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age . "<br/>";
    echo "Address : " . $this->address;
  } 
}


$myobj = new Details;

$myobj->setData("John", 20);
$myobj->setAddress("London, UK-England.");

$myobj->printInfo();

?>
Output :

Name : John
Age : 20
Address : London, UK-England.

At the above example, we define a child class Details from parent class Student.

Example 2 :
<?php

class Student {
  var $name;
  var $age;

  function __construct($arg1, $arg2) {
    $this->name = $arg1;
    $this->age = $arg2;
  }

  function showData() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age;
  }

}

class Details extends Student {
  var $address;

  function __construct($arg1, $arg2, $arg3) {
    parent::__construct($arg1, $arg2);
    $this->address = $arg3;
  }

  function printInfo() {
    echo "Name : " . $this->name . "<br/>";
    echo "Age : " . $this->age . "<br/>";
    echo "Address : " . $this->address;
  } 
}


$myObj1 = new Details("John", 20, "London, UK-England.");
$myObj1->printInfo();

echo "<br/><br/>";

$myObj2 = new Student("Marry", 19);
$myObj2->showData();

?>
Output :

Name : John
Age : 20
Address : London, UK-England.

Name : Marry
Age : 19

At the above example the parent keyword is used to access parent member variables.