PHP OOP Constructor: How It Works in a Class with Examples

PHP oop constructor

The OOP constructor initializes an object when it is created in PHP.

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 __construct runs automatically when you create a new object from the class TheClassName.

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:

  1. Properties:
    • $name stores the name of the food.
    • $category stores the category of the food.
  2. Constructor (__construct method):
    • This method runs when a new Food object is created.
    • It assigns values to $name and $category.
    • It uses "Unknown" as the default if no values are provided.
  3. Method (getDetails):
    • Returns a string with the food name and category.
  4. Creating objects ($food1 and $food2):
    • $food1 = new Food("Pizza", "Fast Food"); → Assigns “Pizza” and “Fast Food” to $name and $category.
    • $food2 = new Food(); → Uses the default values "Unknown" for both properties.
  5. Output:
    • echo $food1->getDetails(); → Displays: Name: Pizza, Category: Fast Food
    • echo $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.

php support one single constructor

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?

A constructor in object-oriented programming (OOP) is a special method that is automatically called when an object is created. The constructor is defined using the __construct() method. It is used to initialize object properties and set default values. It also used for prepare resources.

Can we overload constructors in PHP?

No, PHP does not support constructor overloading directly (having multiple constructors with different parameter sets). However, you can achieve similar functionality by using:
  • Factory Methods (recommended way).
  • Default Parameters.
  • func_get_args() (to handle variable arguments).

Can you do OOP in PHP?

Yes, PHP fully supports object-oriented programming (OOP). You can define classes, create objects, and use OOP principles like inheritance, encapsulation, polymorphism, and abstraction.

Can a PHP class have multiple constructors?

A PHP class cannot have multiple constructors. Only one __construct() method is allowed. You can use factory methods or optional parameters to provide different ways to create an object to handle multiple initialization methods.

How to call a parent constructor?

You call a parent class constructor with the parent::__construct() method inside the child class’s constructor. This allows the child class to inherit and extend the parent's initialization logic. Here is an example:
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

IF-Else: Executes the IF-Else Statement in PHP

Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

PHP Multidimensional Arrays: Data Manipulation

In web development, managing and manipulating data is one of the most common tasks. When it comes to storing complex…

PHP Syntax: Standard Tags, Echo, and Short Tags

Understanding PHP syntax is like the basics of any language—PHP syntax defines the rules for writing code that a server…

PHP JSON Handling with json_encode & json_decode

JSON is used in most of your web applications for dealing with data, and so, in a way, PHP JSON…

PHP require_once and require

Essentially, “require” and “require_once” are directives in PHP to include and evaluate a specific file during the execution of a…

PHP if-elseif Statement: ‘elseif’ versus ‘else if’

PHP’s if-elseif statement is a fundamental construct that allows developers to control the flow of their code based on different conditions. In…

PHP implode Function: Join Array Values into a String

The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…

Static Method in PHP: How They Work in Classes

PHP static method lets you call functions without an object. In this article, we will cover the following topics: The…

PHP array_keys: How to Extract Keys in Arrays with Examples

This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…

PHP NOT ( ! ) Operator: A Comprehensive Guide

The NOT operator in PHP (!) provides the reverse of whatever truth value is given by a certain expression. It’s…

Previous Article

PHP Class Destructor: How It Works with Examples

Next Article

PHP Access Modifiers: How Public, Private & Protected Work

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.