PHP OOP Inheritance

PHP OOP – Inheritance

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


🟩 1️⃣ Basic Inheritance Example


 


🟦 2️⃣ Child Class Adds Its Own Features


 


🟥 3️⃣ Child Class Overriding Parent Method (Very Important)

Child class can replace a parent method.


 


🟧 4️⃣ Using parent:: to Call Parent Method



 


🟪 5️⃣ Inheritance with Properties

 


🟫 6️⃣ 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:


 


🟨 7️⃣ Protected with Inheritance

Protected properties/methods can be used inside child class:



 


🟦 8️⃣ Real-Life Practical Example

Parent Class: Vehicle

 

Child Classes:


 


🧠 Summary Table

Term Meaning
Parent class Base class
Child class Inherits from parent
extends Used to implement inheritance
Overriding Child replaces parent method
parent:: Calls parent method/constructor

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *