The __destruct method
Learn to clean up resources when an instance is destroyed with __destruct.
The __destruct method
The opposite of the constructor is the destructor: __destruct. It is called automatically when the instance is destroyed. An instance is destroyed when the script ends or the last reference to it is gone.
class TempFile {
public function __construct() {
echo "Opened\n";
}
public function __destruct() {
echo "Closed\n";
}
}The common use of the destructor is resource cleanup: closing open files, releasing database connections or unlocking locks. PHP already frees memory at script end, so the destructor is usually not needed, but it helps with external resources.
Like the constructor, the destructor is not expected to return a value.
Resource cleanup
The destructor is usually not needed, because PHP frees all memory automatically at script end. But it helps with external resources: opening and closing a file, releasing a database connection, unlocking a cache lock.
public function __destruct() {
fclose($this->handle);
}Here the open file is closed when the instance is destroyed. Still, the safest approach is to close the resource manually as soon as you're done with it; the destructor should not replace that, but act as a last resort.
Exercise Add constructor and destructor to the Session class
Define a class named Session. The constructor __construct() should print echo "Session opened\n"; in the body. The destructor __destruct() should print echo "Session closed\n"; in the body. Below the class create an instance with $s = new Session();. PHP calls the destructor at script end, so you'll see two output lines.
Show example solution
Write the constructor as public function __construct() with echo "Session opened\n"; in the body. Write the destructor as public function __destruct() with echo "Session closed\n"; in the body. Outside the class create an instance with $s = new Session();.
Example solution:
<?php
// Define the Session class, add constructor and destructor
class Session {
public function __construct() {
echo "Session opened\n";
}
public function __destruct() {
echo "Session closed\n";
}
}
$s = new Session();
Test yourself
-
Complete the destructor method name
public function ____() { echo "Closed\n"; }Show answer
public function __destruct() { echo "Closed\n"; } -
Match the concepts
- __construct
- runs at birth
- __destruct
- runs at destruction
- fclose
- closes a file
- magic method
- magic method category
-
When is __destruct called?
- When the instance is created with new
- When a method is called
- When the instance is destroyed, at script end or when the reference is gone
- When the class is declared
Show answer
When the instance is destroyed, at script end or when the reference is gone — Correct. __destruct runs when the instance is removed from memory; this is usually at script end.