OnlineCBT Logo OnlineCBT
PHP · LESSON 17

Constructors (__construct) and Destructors

By Ratan Updated: 16 Oct 2026

Initialize object state automatically with __construct() and clean resources with __destruct().

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

1. The Constructor Method (__construct)

The constructor is a magic method automatically called whenever a new instance of a class is instantiated with the new keyword. It is typically used to initialize object properties and inject dependencies.

title = $title;
        $this->durationMinutes = $durationMinutes;
        $this->totalQuestions = $totalQuestions;
    }

    public function getSummary(): string {
        return "{$this->title}: {$this->totalQuestions} questions ({$this->durationMinutes} mins)";
    }
}

$physicsExam = new Exam("NEET Physics Mock Test", 180, 45);
echo $physicsExam->getSummary();

2. PHP 8 Constructor Property Promotion

Modern PHP 8 introduced constructor property promotion, eliminating repetitive property declarations and assignments:

title; // Organic Chemistry

3. The Destructor Method (__destruct)

The destructor is invoked automatically when an object is no longer referenced or when the PHP script finishes execution. It is useful for cleaning up open resources, closing database sockets, or flushing temporary cache files.

fileHandle = fopen($filePath, "a");
    }

    public function log(string $message): void {
        fwrite($this->fileHandle, "[" . date("Y-m-d H:i:s") . "] " . $message . "\n");
    }

    public function __destruct() {
        if ($this->fileHandle) {
            fclose($this->fileHandle);
        }
    }
}

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
पता संपर्क करें

+91 7877547686

ई-मेल

onlinecbtportal@gmail.com

हेल्पलाइन नंबर

+91 7877547686


डाउनलोड करने के लिए क्लिक करें
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat