The OOP constructor initializes an object when it is created in PHP.
Table of Content
Understand What a Constructor Is in PHP
A constructor in PHP is a special method inside a class that runs automatically when an object is created. It has the name __construct(). You can use it for the following reasons:
- Set default values.
- Establish database connections
- Prepare other resources when an object is initialized.
This helps you to reduce code repetition and improve your web application performance. It also automates setup tasks when it creates multiple objects.
Here is the syntax:
class TheClassName {
public function __construct() {
// Here the initialization code
}
}How it works:
- A class is like a plan to make objects.
- The function
__constructruns automatically when you create a new object from the classTheClassName.
So, when you call this class like this:
$object = new TheClassName();The __construct function is executed directly.
So, how does the constructor work in PHP?
It runs by itself when you create a new object:
- Defines initialization code – The constructor method (
__construct) is inside a class. It contains code that runs when an object is created. - Accepts parameters – You can pass values to the constructor, which it assigns to properties.
- Runs automatically – PHP calls the constructor without needing extra steps when you create an object.
For example:
class Box {
public $length;
public $width;
// Constructor runs when a new object is created
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
// Method to show details
public function getDetails() {
return "Length: $this->length, Width: $this->width";
}
}
// Create objects from the class
$box1 = new Box(10, 5);
// Print the details
echo $box1->getDetails();Here is the output:
Length: 10, Width: 5
This creates a class “Box” with length and width. When you create new Box(10, 5), it stores 10 as length and 5 as width. The function getDetails() just shows these values, so echo $box1->getDetails(); prints: Length: 10, Width: 5.
Pass Default Values in Constructor
You can set default values in a PHP constructor and assign values to parameters. This lets you create objects, and you don’t need to set arguments with it.
Here is an example:
class Food {
public $name;
public $category;
public function __construct($name = "Unknown", $category = "Unknown") {
$this->name = $name;
$this->category = $category;
}
public function getDetails() {
return "Name: $this->name, Category: $this->category";
}
}
$food1 = new Food("Pizza", "Fast Food");
$food2 = new Food();
echo $food1->getDetails();
echo $food2->getDetails();The output:
Name: Pizza, Category: Fast FoodName: Unknown, Category: Unknown
Here is how it works:
- Properties:
$namestores the name of the food.$categorystores the category of the food.
- Constructor (
__constructmethod):- This method runs when a new
Foodobject is created. - It assigns values to
$nameand$category. - It uses
"Unknown"as the default if no values are provided.
- This method runs when a new
- Method (
getDetails):- Returns a string with the food name and category.
- Creating objects (
$food1and$food2):$food1 = new Food("Pizza", "Fast Food");→ Assigns “Pizza” and “Fast Food” to$nameand$category.$food2 = new Food();→ Uses the default values"Unknown"for both properties.
- Output:
echo $food1->getDetails();→ Displays:Name: Pizza, Category: Fast Foodecho $food2->getDetails();→ Displays:Name: Unknown, Category: Unknown.
Constructor Overloading in PHP OOP
Constructor overloading refers to multiple constructors with different argument lists. PHP does not support multiple constructors directly.

You can do the same thing with methods that manage arguments, like:
- Default Values.
func_get_args().- Named Parameters (PHP 8.0+).
- Factory methods.
Here is an example of factory methods.
class Machine {
private $type;
private $power;
private $manufacturer;
private function __construct() {
// Shared initialization logic (if needed)
}
public static function createWithType($type) {
$machine = new self();
$machine->type = $type;
return $machine;
}
public static function createWithTypeAndPower($type, $power) {
$machine = new self();
$machine->type = $type;
$machine->power = $power;
return $machine;
}
public static function createFullMachine($type, $power, $manufacturer) {
$machine = new self();
$machine->type = $type;
$machine->power = $power;
$machine->manufacturer = $manufacturer;
return $machine;
}
public function display() {
echo "Type: {$this->type}, Power: {$this->power}, Manufacturer: {$this->manufacturer}\n";
}
}
$basicMachine = Machine::createWithType("Drill");
$basicMachine->display();
$advancedMachine = Machine::createWithTypeAndPower("Lathe", 1500);
$advancedMachine->display();
$fullMachine = Machine::createFullMachine("Press", 3000, "MegaCorp");
$fullMachine->display(); Output:
Type: Drill, Power: , Manufacturer:
Type: Lathe, Power: 1500, Manufacturer:
Type: Press, Power: 3000, Manufacturer: MegaCorp
Here, I used the Factory Pattern to make objects in PHP. That does not require using the constructor directly.
The constructor is private, so you must use one of three static methods. createWithType() sets only the type. createWithTypeAndPower() sets type and power. createFullMachine() sets type, power, and manufacturer.
Each method uses the private constructor to make the object and return it.
Call Parent Constructors in Inheritance
You can use parent::__construct() to run the parent class constructor. This helps a child class set up properties or actions from the parent.
Here is an example:
class Motorcycle {
protected $engineType;
public function __construct($engineType) {
$this->engineType = $engineType;
}
}
class SportBike extends Motorcycle {
private $brand;
public function __construct($engineType, $brand) {
parent::__construct($engineType);
$this->brand = $brand;
}
public function showDetails() {
echo "Engine: {$this->engineType}, Brand: {$this->brand}\n";
}
}
$bike = new SportBike("600cc", "Yamaha");
$bike->showDetails();Here is the output:
Engine: 600cc, Brand: Yamaha
Here, it creates Motorcycle that stores the engine type. SportBike extends it and adds a brand. Then, it sets both in the constructor. The showDetails() method prints the engine type and brand of the bike object.
PHP 8 Constructor Property Promotion
In old versions, you had to write class properties first and then assign them again inside the constructor. PHP 8 introduced a new way called constructor property promotion.
With this feature, you can declare and set them in one step inside the constructor parameter list.
So, instead of this (without property promotion):
class Customer {
public string $name;
public int $order;
public function __construct(string $name, int $order) {
$this->name = $name;
$this->order= $order;
}
}You can write it with this (property promotion):
class Customer {
public function __construct(
public string $name,
public int $order
) {
}
}Here is how it works:
- You can use access modifiers with constructor parameters.
- PHP makes and sets these properties.
- It works with typed properties, and that helps with validation.
- You can mix promoted and normal parameters when you need it.
Examples of a Constructor in PHP
User Profile Setup:
class UserProfile {
public $name;
public $age;
public function __construct($userName, $userAge) {
$this->name = $userName;
$this->age = $userAge;
}
}
$user = new UserProfile("Montasser", 38);
echo $user->name;It sets the name and age when the object is created.
Product Price with Tax:
class ProductPrice {
public $price;
public $tax;
public function __construct($basePrice, $taxRate = 0.1) {
$this->price = $basePrice;
$this->tax = $basePrice * $taxRate;
}
}
$item = new ProductPrice(100);
echo $item->tax;It adds a tax value to the product price with a default rate.
Database Connector:
class DBConnector {
public $connection;
public function __construct($host, $db) {
$this->connection = "Connected to $db at $host";
}
}
$conn = new DBConnector("localhost", "shopDB");
echo $conn->connection;This stores a simple database connection message.
Book Record (Constructor Property Promotion Feature of PHP 8):
class Book {
public function __construct(
public string $title,
public string $author
) {}
}
$book = new Book("1984", "George Orwell");
echo $book->title . " by " . $book->author;This makes a book record with the title and author in one step.
Wrapping Up
You learned how the PHP OOP constructor works in PHP and how to use it in object-oriented programming.
Here’s a quick recap:
A constructor in PHP is a method called __construct() that runs automatically when an object is created.
You can use it to do the below:
- Initialize object properties.
- Set default values.
- Establish database connections.
- Prepare other resources.
- Property promotion in PHP 8 saves you from extra code since it joins property declaration and assignment inside the constructor.
FAQ’s
What is a constructor in OOP?
Can we overload constructors in PHP?
- Factory Methods (recommended way).
- Default Parameters.
- func_get_args() (to handle variable arguments).
Can you do OOP in PHP?
Can a PHP class have multiple constructors?
How to call a parent constructor?
class Machine {
public function __construct($type) {
$this->type = $type;
}
}
class Car extends Machine {
public function __construct($type, $brand) {
parent::__construct($type);
$this->brand = $brand;
}
}Similar Reads
PHP 8.4 released the array_any to test if at least one element matches a condition. Understand the array_any Function in…
The PHP array_fill_keys function helps you to build an array where each key has the same value. What is the…
There are some tools known as "PHP magic constants" that will make your code a little more clever and versatile.…
The array_pop function in PHP gives you a direct way to take the last element from an array. Understand the…
The array_key_last gives you the last key in an array and works with numeric and associative arrays in PHP. It…
You can use the array_fill function in PHP when you must fill an array with one value. You may want…
The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…
The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…
You use PHP every day if you build websites, but most people do not know where it came from or…
Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…