Destructor (__destruct)
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 8 of 91.
The __destruct method is a special method that is automatically called when an object is destroyed. An object is destroyed when there are no more references to it or when the script ends.
Here is an example of a class with both a constructor and a destructor:
<?php
class Resource {
public $name;
public function __construct($name) {
$this->name = $name;
echo $this->name . " was created\n";
}
public function __destruct() {
echo $this->name . " was destroyed\n";
}
}Create an object and watch the lifecycle:
echo "=== Start ===\n";
$r = new Resource("Connection");
echo "Using " . $r->name . "\n";
unset($r); // explicitly destroy the object
echo "=== End ===\n";Output:
=== Start ===
Connection was created
Using Connection
Connection was destroyed
=== End ===The unset() function removes the reference to the object, triggering the destructor immediately.
If you don't call unset(), the destructor runs automatically when the script finishes:
$r = new Resource("Logger");
echo "Working...\n";
// __destruct is called automatically at end of scriptOutput:
Logger was created
Working...
Logger was destroyedKey Point: The __destruct method is useful for cleanup tasks like closing files, releasing resources, or logging when an object is no longer needed.
Challenge
MediumComplete the Resource class in resource.php:
- Add a
__constructmethod that takes$name, sets it as a property, and prints"[name] was created" - Add a
logMessagemethod that takes$messageand prints"Log: [message]" - Add a
__destructmethod that prints"[name] was destroyed"
The driver.php file will test the lifecycle of your Resource objects.
Cheat sheet
The __destruct method is automatically called when an object is destroyed (when there are no more references to it or when the script ends).
Example of a class with constructor and destructor:
<?php
class Resource {
public $name;
public function __construct($name) {
$this->name = $name;
echo $this->name . " was created\n";
}
public function __destruct() {
echo $this->name . " was destroyed\n";
}
}The unset() function removes the reference to an object, triggering the destructor immediately:
$r = new Resource("Connection");
unset($r); // explicitly destroy the objectIf unset() is not called, the destructor runs automatically when the script finishes.
The __destruct method is useful for cleanup tasks like closing files, releasing resources, or logging.
Try it yourself
<?php
require_once 'resource.php';
$testCase = trim(fgets(STDIN));
if ($testCase == "basic_test") {
echo "=== Start ===\n";
$r = new Resource("FileHandler");
echo "Using " . $r->name . "\n";
unset($r);
echo "=== End ===\n";
} elseif ($testCase == "auto_destruct_test") {
$r = new Resource("Logger");
$r->logMessage("Application started");
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern