PHP OOP Constructor

PHP OOP Constructor Explained
1. Syntax of Constructor in PHP
2. Why Use a Constructor?
- Initialize object values
- Set default data
- Open database connections
- Run code only once when object is created
3. Basic Constructor Example
Output:
A new car is created!
4. Constructor With Parameters
Most useful form.
We pass values when creating the object.
Brand: Toyota, Color: Red
5. Using Constructor to Set Default Values
6. Constructor Overloading (PHP Trick)
PHP does not support multiple constructors directly,
but we can simulate it:
7. Real-Life Practical Constructor Example
Auto connecting to database when object is created:
Summary
| Feature | Meaning |
|---|---|
__construct() | Auto run method |
| Parameters | Set values when object creates |
$this | Refers to current object |
| Default values | Create simple overloaded constructors |
| Best use | Initialize object data |
