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);
}
}
}