Core PHP

A Class with Inheritance

Classes can use inheritance to inherit the members of another class. Inheritance is achieved by adding the keyword "extends" to a class, along with the name of the class to be inherited.

Below, we have defined three classes: CMass, CPriest, and CBishop. The CMass class is a class on it own. However, CPriest is a base class that the class CBishop inherits. This relationship mirrors the fact that every bishop is a priest. Generally, when a class inherits another class, it is because the inheriting object type is also an object of the type of the base class.

The inheriting class, CBishop, creates a base object of type CPriest inside itself, when a CBishop object is created. This construction of the base class object is accomplished inside the CBishop constructor, when we call the parent class with the line parent::__construct($sName);.

In the program below, we instantiate a CBishop with the name "Valerius" passed into the contructor. Then we echo out the object's name. Next, we call OrdainPriest() via this object with the name "Augustine" to create a new priest object; this corresponds to the priestly ordination of "Augustine of Hippo," who is now a Catholic Church Father. After this, we echo out the name of this new priest object. Finally, we call the CelebrateMass() method for both the bishop and priest objects to create a CMass object for each, and echo out the name of each celebrant through of these CMass objects.

Notice that a CBishop object can call OrdainPriest(), but a CPriest can not. However, both can call CelebrateMass() because the CBishop objects have access to the method through inheritance.

Inheritance.php

<?php
  class CMass {
    var $mqCelebrant;

    public function __construct($qCelebrant) {
      $this->mqCelebrant = $qCelebrant;
    }
  }

  class CPriest {
    var $msName;

    public function __construct($sName) {
      $this->msName = $sName;
    }

    public function CelebrateMass() {
      return new CMass($this);
    }
  }

  class CBishop extends CPriest{

    public function __construct($sName) {
      parent::__construct($sName);
    }

    public function OrdainPriest($sPriestsName) {
      return new CPriest($sPriestsName);
    }
  }

  $qBishopValerius = new CBishop("Valerius");
  echo "Bishop ".$qBishopValerius->msName."<br />";

  $qFatherAugustine = $qBishopValerius->OrdainPriest("Augustine");
  echo "Father ".$qFatherAugustine->msName."<br />";

  $qMass1 = $qBishopValerius->CelebrateMass();
  $qMass2 = $qFatherAugustine->CelebrateMass();
  echo "Mass 1 Celebrant: ".$qMass1->mqCelebrant->msName."<br />";
  echo "Mass 2 Celebrant: ".$qMass2->mqCelebrant->msName."<br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.