Blog

A Brief Explanation of Class Inheritance in PHP
Posted on June 23, 2015 in OOP, PHP by Matt Jennings

In PHP, an inherited class (also called an extended class or subclass) usually gets all of the parent class’s methods and/or properties. Below is an example:

// Parent class
class Human
{
  // "Human" class methods and properties here
  public function humanFunction()
  {
    echo 'humanFunction called!';
  }
}

/*
The "Wizard" class below is a subclass
(or extended or inherited class) of the "Human" class AND
usually inherits all of the "Human" class methods and properties
*/
class Wizard extends Human
{
  // Properties and methods ONLY available to "Wizard" class here
  public function wizardFunction()
  {
    echo 'wizardFunction called!';
  }
}

// "Wizard" subclass instantiation 
$harry = new Wizard();

// "Wizard" subclass calls the "humananFunction()" method
// from the "Human" parent class and the output is:
// "humanFunction called!"
$harry->humanFunction();

 

Leave a Reply

To Top ↑