OOP PHP Lesson 5 – Inheritance and scope resolution operator

featured image for php oop lesson 5 - basics

Inheritance means that you can derive classes from a parent class, and all methods and properties of parent class will be accessible in the new class. This way we can quickly and easily expand functionality of some class, just by adding new properties and methods.

Inheritance is done by using keyword extends, like in the listing of Person class below (Person.php file). We want to create class Person, not from the scratch, but using inheritance:

require_once('Customer.php');

class Person <strong>extends</strong> Customer {

   function __construct() {
   parent::__construct();
}

function __destruct() {
   parent::__destruct();
}

private $age=0;

public function set_age($person_age) {

   if($this->age==0) {

      $this->age = $person_age;

   }

   else {
      echo 'Person\'s age has already been set is set: '.$this->age.'<br />';
   }
}

public function get_age() {

echo 'Person\'s age is: '.$this->age.'<br />';

 }

}

As you can see above, we create class called Person. However, Customer class has some useful features – for instance setting name of a customer – which could be useful in Person class too, for setting name of a person. So, instead of writing all the code again we use inheritance: Person class (child class) extends Customer class (parent class). Customer.php file has to be included in definiton file of Person class, because Customer class is needed in process of creation of Person class.

Additionally in both constructor and destructor methods of Person class we reach for content of the methods in parent class (that is Customer class), using keyword parent and scope resolution operator :: used for direct access to methods and properties of parent (base) class. We can add something more in constructor and destructor of Person class, to extend its functionality, if needed. To simplify the example, Person class is extended only by adding option of setting and getting a person age, as seen below:

function __autoload($classname) {

   $classfile = "./". $classname .".php";
   require_once($classfile);

}

$a_person = new Person();
$a_person->set_name("Steven");
$a_person->get_name();
$a_person->say_hello();
$a_person->set_age(20);
$a_person->get_age();
$a_person->set_age(30);

unset($a_person);

Customer class definition (in Customer.php file) remains unchanged.

No doubt, that inheritance is powerful feature of object oriented programming which enables code reusability and simplify child classes creation.