Constructors & Destructors in PHP

Introduction

In Object-Oriented Programming (OOP), constructors and destructors are special methods that automatically run at specific moments in an object’s lifecycle.

A constructor runs when an object is created, while a destructor runs when an object is destroyed.

These methods help developers manage object initialization and cleanup efficiently. Instead of manually setting values after creating an object, constructors allow you to prepare the object immediately. Destructors help release resources like database connections or file handlers when the object is no longer needed.

This makes your code cleaner, safer, and more professional.

What You’ll Learn

In this tutorial, you will learn:

  • what constructors are
  • how __construct() works
  • what destructors are
  • how __destruct() works
  • real-world use cases of both methods

👉 Understanding constructors and destructors is an important step toward writing professional OOP code in PHP.

What is a Constructor in PHP?

A constructor is a special method that is automatically called when an object is created.

In PHP, a constructor is defined using the __construct() method.

It is mainly used to:

  • Initialize properties
  • Set default values
  • Prepare the object for use

Why Do We Need Constructors?

Without constructors, you must manually set values after creating an object.

With constructors:

  • Code becomes cleaner
  • Object is ready immediately
  • Fewer chances of mistakes
  • Initialize object properties
  • Ensure required values are provided

Constructor Example (Basic)

<?php
class User {
    public $name;

    public function __construct() {
        $this->name = "Guest";
    }
}
?>

Explanation:

  • __construct() runs automatically
  • $name is set as soon as object is created

Example Without Constructor

<?php
class Car {
    public $brand;
}$car1 = new Car();
$car1->brand = "Toyota";
?>

Here, we assign the property manually after creating the object.

Example With Constructor

<?php
class Car {
    public $brand;    public function __construct($brand) {
        $this->brand = $brand;
    }
}$car1 = new Car("Toyota");
?>

Now the object is initialized immediately when created.

Creating Object with Constructor

<?php
$user = new User();
echo $user->name;
?>

Output:

Guest

Constructor with Parameters

You can pass values while creating the object.

<?php
class User {
    public $name;
    public $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }
}
?>

Passing Values to Constructor

<?php
$user = new User("Divyesh", "div@example.com");

echo $user->name;
echo $user->email;
?>

Now the object is initialized immediately with values.

Multiple Constructors? (Important Note)

PHP does NOT support multiple constructors.

But you can simulate this by:

  • Using optional parameters
  • Using default values
public function __construct($name = "Guest") {
    $this->name = $name;
}

What is a Destructor in PHP?

A destructor is a special method that runs when an object is destroyed.

It is defined using __destruct().

Destructors are used to:

  • Close database connections
  • Free resources
  • Perform cleanup tasks

Destructor Example

<?php
class Database {
    public function __construct() {
        echo "Connection opened";
    }

    public function __destruct() {
        echo "Connection closed";
    }
}
?>

When is Destructor Called?

Destructor is called when:

  • Script execution ends
  • Object is unset using unset()
<?php
$db = new Database();
unset($db);
?>

Should Beginners Use Destructors?

Destructors are:

  • Not used frequently
  • Helpful in advanced applications
  • Common in database and file handling classes

Understanding them is enough at this stage.

Real-World Use Case

In real projects:

  • Constructor → opens DB connection
  • Destructor → closes DB connection

This ensures proper resource management.

Key Differences Between Constructor and Destructor

ConstructorDestructor
Runs when object is createdRuns when object is destroyed
Used for initializationUsed for cleanup
Can accept parametersCannot accept parameters
Defined as __construct()Defined as __destruct()

Common Mistakes Beginners Make

  • Misspelling __construct or __destruct
  • Forgetting the double underscore
  • Trying to manually call constructors
  • Passing wrong parameters
  • Not understanding when destructor runs

Remember: these methods run automatically.

FAQs

What is a constructor in PHP?

A constructor is a special method that runs automatically when an object is created. It is defined using __construct().

What is a destructor in PHP?

A destructor is a special method that runs automatically when an object is destroyed. It is defined using __destruct().

Can PHP have multiple constructors?

No, PHP does not support multiple constructors directly. You can use optional parameters or default values instead.

Why are constructors useful?

Constructors help initialize object properties immediately and reduce manual setup after object creation.

When should destructors be used?

Destructors are useful when you need cleanup tasks like closing database connections or releasing resources.

Practical Task

Create a class named User:

  • Add a constructor that accepts a username
  • Display a message when the object is created
  • Add a destructor that prints a message when the object is destroyed

Observe when each method runs during script execution.

Conclusion

Constructors and destructors are important parts of Object-Oriented Programming in PHP because they help manage an object’s lifecycle automatically.

A constructor prepares the object when it is created, while a destructor handles cleanup when the object is no longer needed.

Using constructors makes your code cleaner and safer by ensuring objects are initialized properly from the beginning. Destructors help maintain better resource management in larger applications.

These concepts are commonly used in real-world PHP projects like database handling, file management, and framework development.

Once you understand constructors and destructors, learning advanced OOP concepts becomes much easier.

👉 Mastering these small concepts helps you write more professional and scalable PHP code.

In the next tutorial, we’ll learn about Access Modifiers in PHP (public, private, protected).

Related Tutorials

  • OOP in PHP – Introduction to Object-Oriented Programming

    Introduction As PHP projects become larger, managing code using only procedural programming becomes difficult. Files get longer, functions become harder to track, and updating the project takes more time. This is where Object-Oriented Programming (OOP) becomes important. OOP helps developers organize code in a cleaner and more structured way by grouping related data and functionality…

  • Classes & Objects in PHP

    Introduction In Object-Oriented Programming (OOP), classes and objects are the foundation of everything. Once you understand these two concepts clearly, learning advanced OOP topics like constructors, inheritance, and polymorphism becomes much easier. In simple words, a class is a blueprint, and an object is a real instance created from that blueprint. For example, if “Car”…

  • Access Modifiers in PHP (public, private, protected)

    Introduction Access modifiers in PHP control how properties and methods can be accessed inside Object-Oriented Programming (OOP). They help define the visibility of class members and protect important data from unwanted access. With access modifiers, you can decide who can access a property, who can call a method, and whether a value should be changed…

  • Inheritance in PHP

    Introduction Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. In simple words, inheritance helps you reuse existing code instead of rewriting it. This makes your code cleaner, more structured, and easier to maintain. In this tutorial, you will…

  • Encapsulation in PHP

    Introduction Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It refers to the concept of restricting direct access to certain parts of an object and allowing controlled access through methods. In simple words, encapsulation means data hiding. Instead of allowing users to directly access and modify object properties, we protect them using…

  • Polymorphism in PHP

    Introduction Polymorphism is one of the four core principles of Object-Oriented Programming (OOP): The word Polymorphism means “many forms.” In PHP, polymorphism allows different classes to use the same method name but perform different actions. This makes your code flexible, scalable, and easier to maintain. 📌 What is Polymorphism? Polymorphism allows objects of different classes…

Leave a Reply

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