Realtime examples when you had to use __destruct in your classes in PHP
- When creating a custom database connection class: In this example, I created a class to handle database connections using the MySQLi extension. The
__construct
method established a connection to the database when an instance of the class was created, and the__destruct
method closed the connection when the instance was no longer needed. This ensured that the connection was properly closed and freed up resources when the script finished executing. - When creating a custom logging class: In this example, I created a class to handle logging events to a file. The
__construct
method opened the log file when an instance of the class was created, and the__destruct
method closed the file when the instance was no longer needed. This ensured that the file was properly closed and saved any changes when the script finished executing.
In both of these cases, using the __destruct
method allowed me to automatically close connections or files when the instances of the classes were no longer needed, without having to remember to manually close them in the rest of the code.