πŸŽ‰ New: Top 75 PHP Interview Questions for 2026 β€” Free for all learners

Constructor / Destructor – PHP OOP

P
php Guru
Β· February 13, 2023 Β· 4 min read Β· Updated February 13, 2023

πŸ“Œ Key Takeaways

  • Constructor / Destructor – PHP OOP
  • Constructor / Destructor in PHP OOP – Complete Beginner
  • What Is a Constructor in PHP OOP?
  • What Is a Destructor in PHP OOP?
  • How Constructor and Destructor Work Together in PHP
  • PHP Constructor Example with Output (Beginner Friendly)
Advertisement

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.

P
php Guru
← Previous Post
Classes and Objects - PHP OOP
Next Post β†’
Access Modifiers - PHP OOP

Leave a Reply

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

Prove your humanity: 2   +   4   =