PHP Class Inheritance Constructor: You Should Know

Inheritance is very powerful and useful OOP concept that gives flexibility and re-usability to the code in an efficient way. I am going to write about Constructors and Inheritance in this tutorial, and reading of my previous tutorial about PHP5 Class Inheritance Basics is valuable for your knowledge and the concept of PHP Class Inheritance Constructor.

We have missed constructor of child classes in our previous tutorial, but we will learn to write it now.

Child Class Constructor

When you define a constructor in a child class, you become responsible for passing any arguments on to the parent. If you fail to do this, you can end up with a partially constructed object.

The concept is very simple, let break it

Child class may have constructor.

Child class should pass complete arguments to the parent for a fully constructed object.

Keyword parent and ::

To invoke a method in a parent class, you must first find a way of referring to the class itself: a handle. PHP provides us with the parent keyword for this purpose. To refer to a method in the context of a class rather than an object you use :: rather than ->.

Reconstruct our Male and Female Child Classes

It is time to implement our theory into a child class having its own constructor. We will add a new property (chromosome) in our both male and female child classes. We will also implement this new property via constructor of these respective classes.

Name: Mike John
Chromosome: XY
Gender: Male
Mass: Skeletons are larger and heavier
Limbs: The humerus, ulna and radius, which are the major bones that comprise most of the arm, are thicker and longer.
Skull: Jawbone or mandible is typically angular and square-shaped at the chin area.
Pelvis: The coccyx or tailbone, which is the last bone of the spinal column, is less movable.
Name: Martina John
Chromosome: XX
Gender: Female
Mass: Skeletons are not larger and heavier
Limbs: The humerus, ulna and radius, which are the major bones that comprise most of the arm, are not thicker and longer.
Skull: Jawbone tends to be more rounded and pointed.
Pelvis: The coccyx or tailbone, which is the last bone of the spinal column, is more movable.

Points to Remember

These points will help you in the strengthening of PHP Class Inheritance Constructor concept,

For a fully constructed object, you are responsible for passing any arguments on to the parent.

PHP provides the parent keyword to invoke a method in a parent class.

To refer to a method in the context of a class rather than an object you use :: rather than ->.

Each child class invokes the constructor of its parent before setting its own properties. so the base class knows only about its own data.

Child classes are generally specializations of their parents. As a rule of thumb, you should avoid giving parent classes any special knowledge about their children.