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
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:
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
| 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 |
