Constructor / Destructor – PHP OOP

Constructor / Destructor in PHP OOP – Complete Beginner-Friendly Guide

Constructors and destructors are two essential concepts in PHP Object-Oriented Programming (OOP) that help manage object initialization and cleanup.
They make your code efficient, organized, and professional.

This guide explains everything step-by-step with clear examples, real output, and SEO-rich long-tail keywords to help learners and developers master PHP OOP.


What Is a Constructor in PHP OOP?

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

It is defined using the magic method:

__construct()

Why Constructors Are Important

  • Automatically set initial values
  • Load required dependencies
  • Execute startup tasks
  • Improve clean and structured coding

PHP Constructor Syntax

class ClassName {
    public function __construct() {
        // Code that runs automatically
    }
}

What Is a Destructor in PHP OOP?

A destructor is a special method in PHP that automatically runs when an object is destroyed or script execution ends.

It is defined using:

__destruct()

Why Destructors Are Used

  • Close database connections
  • Release system resources
  • Write log data
  • Free memory
  • Perform final cleanup tasks

PHP Destructor Syntax

class ClassName {
    public function __destruct() {
        // Cleanup code
    }
}

How Constructor and Destructor Work Together in PHP

When you create an object:

  1. Constructor runs first
  2. Program executes other methods
  3. Destructor runs automatically at the end

This ensures smooth startup and cleanup.


PHP Constructor Example with Output (Beginner Friendly)

<?php
class User {
    public function __construct() {
        echo "Constructor: Object Created<br>";
    }

    public function sayHello() {
        echo "Hello User!<br>";
    }

    public function __destruct() {
        echo "Destructor: Object Destroyed";
    }
}

$obj = new User();
$obj->sayHello();
?>

Output:

Constructor: Object Created
Hello User!
Destructor: Object Destroyed

This example shows how constructors initialize the object and destructors finalize the lifecycle.


PHP Constructor with Parameters

<?php
class Student {
    public $name;
    public $course;

    public function __construct($name, $course) {
        $this->name = $name;
        $this->course = $course;
        echo "Welcome $name, You enrolled in $course<br>";
    }

    public function __destruct() {
        echo "Student data removed.";
    }
}

$s = new Student("John", "PHP OOP");
?>

Output:

Welcome John, You enrolled in PHP OOP
Student data removed.

Why Use Constructors with Parameters?

Using parameters inside constructors helps in:

  • Initializing objects with dynamic values
  • Reducing code duplication
  • Improving flexibility and readability

Example uses include:
– Login sessions
– User data loading
– Product initialization


Real-Life Use Case: Database Connection Using Constructor / Destructor

<?php
class Database {
    private $conn;

    public function __construct() {
        $this->conn = "Database Connected!";
        echo $this->conn . "<br>";
    }

    public function query() {
        echo "Running Query...<br>";
    }

    public function __destruct() {
        echo "Database Connection Closed";
    }
}

$db = new Database();
$db->query();
?>

Output:

Database Connected!
Running Query...
Database Connection Closed

This is how real applications handle database connections using constructor and destructor.


Difference Between Constructor and Destructor

FeatureConstructorDestructor
PurposeInitialize objectClean up resources
Runs whenObject is createdObject is destroyed
Method name__construct()__destruct()
Accepts parameters?YesNo
Called manually?YesNot recommended
PHP constructor, PHP destructor, PHP OOP constructor example, PHP magic methods, object-oriented PHP tutorial, PHP OOP basics, PHP class constructor, PHP __construct, PHP __destruct, PHP OOP lifecycle

Best Practices for Using Constructors and Destructors in PHP

  • Keep constructors lightweight
  • Use destructors for resource cleanup only
  • Avoid heavy logic inside destructors
  • Use constructor parameters for flexibility
  • Always release database connections

Frequently Asked Questions (FAQ)

1. Is a constructor mandatory in PHP?

No. If you do not create one, PHP provides a default constructor.

2. Can a PHP class have multiple constructors?

No. PHP allows only one __construct() method.

3. When does the destructor run?

At the end of script execution or when there are no references left to the object.

4. Can a destructor accept parameters in PHP?

No. Destructors cannot accept parameters.

5. Are constructors and destructors inherited?

Yes. Child classes inherit them, but you can override them.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments