PHP OOP Constructor

🔷 PHP OOP – Constructor Explained

A constructor is a special method inside a class that runs automatically when an object is created.

✅ 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.


Output:

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

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 *