A destructor is called when an object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script's execution.
While constructors are used to initialize an object, destructors are used to clean up. This is commonly used to close database connections, close open files, or write log messages before the object is removed from memory.
Like the constructor, the destructor starts with two underscores (__). It does not take any arguments.
In the example above, the destructor is called automatically at the very end of the script. Even though we didn't explicitly call a method to print the name, the __destruct() function executed as soon as the script finished and the $apple object was destroyed.
You don't always have to wait for the script to end. You can trigger the destructor immediately by setting the object variable to null or using the unset() function.
| Feature | Constructor (__construct) | Destructor (__destruct) |
|---|---|---|
| Timing | Called when object is created. | Called when object is destroyed. |
| Arguments | Can accept parameters. | Cannot accept parameters. |
| Usage | Setting up initial values. | Closing resources/cleaning up. |