PHP Tutorial PHP Advanced PHP References

PHP - Inheritance



Inheritance enables a class to inherit all public and protected properties and methods from another class. The class which is being inherited is called base class or parent class. The class which inherits from another class is called derived class or child class. Inheritance provides re usability of a code and adds more features to a class without modifying it.

Create derived Class

To create a derived class, it is must to specify PHP extends keyword. See the syntax below. A derived class inherits all public and protected members of base class.

Syntax

//defining a class
class base_class {
  class members;
};

//defining a derived class
class derived_class extends base_class {
  code statements;
};

Example:

In the example below, a base class called Person is created which has two properties called name and age. Student, a derived class of Person is also created. The derived class Student inherits all public and protected properties and methods of base class Person.

<?php
class Person {
  public $name = "John";
  public $age = 15; 
};

//Student is the derived class of Person
class Student extends Person {
  public $grade = "ninth grade"; 
};

$s1 = new Student();
echo $s1->name." studies in ".$s1->grade.".\n";
echo $s1->name." is ".$s1->age." years old."; 
?>

The output of the above code will be:

John studies in ninth grade.
John is 15 years old.

Access Specifier of Inherited members