Last revision:
Introduction
Destructors are special class methods that are automatically invoked when objects are deleted or the PHP script terminates,
Destructors are typically used to perform cleanup actions, such as closing a database connection or file handle, or freeing up memory that is no longer needed.
Destructors must always be named `__destruct()` and must be declared public.
Example
This imaginary Logger class has:
- a constructor for initializing properties and opening a database connection
- a destructor for closing the database connection
By opening the connection in the constructor and closing it in the destructor, developers using this class don't need to think about opening and closing database connections: it all happens automatically.
Summary
- Destructors are special class methods that are automatically invoked when objects are deleted or the PHP script terminates.
- Destructors are typically used to clean up resources.
- Syntax:
public function __destruct() { //Code goes here. }, without any parameters.