PHP OOP Constructor

PHP Tutorial

PHP OOP Constructor Explained

PHP OOP 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

FeatureMeaning
__construct()Auto run method
ParametersSet values when object creates
$thisRefers to current object
Default valuesCreate simple overloaded constructors
Best useInitialize object data

You may also like...