PHP Destructor
A destructor in PHP serves as a special method within a class that PHP automatically executes when the object is destroyed or exits its scope at the script's end or upon unset.
In PHP, destructors are useful for:
- Releasing resources (closing files, DB connections)
- Logging or cleanup actions
- Auto-saving changes before shutdown
Syntax
class ClassName {
function __destruct() {
// cleanup code here
}
}
- It has no parameters
- Only one destructor per class
- PHP triggers this method automatically when the object becomes unnecessary
Example
<?php
class User {
public $name;
function __construct($name) {
$this->name = $name;
echo "User '$name' created.<br>";
}
function __destruct() {
echo "User '$this->name' destroyed.<br>";
}
}
$user1 = new User("Alice");
$user2 = new User("Bob");
echo "Script continues...<br>";
// Destructors will be called automatically at the end
?>
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com