PHP OOP Inheritance
PHP OOP – Inheritance
-
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:
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 |
