PHP OOP Inheritance

PHP Tutorial

PHP OOP Inheritance

PHP OOP Inheritance allows a class (child) to take properties and methods from another class (parent).
  • Parent class = Base class (super class)

  • Child class = Derived class (sub class)


Why Use Inheritance?

  •  Reuse code
  •  Avoid duplication
  •  Create hierarchical structure
  •  Extend existing functionality
  •  Used heavily in Laravel controllers & models

Basic Inheritance Example


 


 Child Class Adds Its Own Features


 


Child Class Overriding Parent Method (Very Important)

Child class can replace a parent method.


 


 Using parent:: to Call Parent Method


Inheritance with Properties


Constructor in Inheritance

Parent constructor auto runs when creating child object:


 

Output:

Child constructor

Parent constructor does not run automatically if overridden.

To run both:


 


Protected with Inheritance

Protected properties/methods can be used inside child class:


 Real-Life Practical Example

Parent Class: Vehicle

Child Classes:


 


 Summary Table

TermMeaning
Parent classBase class
Child classInherits from parent
extendsUsed to implement inheritance
OverridingChild replaces parent method
parent::Calls parent method/constructor

You may also like...