Back to results for “Exception Handling”
PHP › Magic Methods

What are magic methods in PHP, and how do the __construct and __destruct methods represent two of the most commonly used examples?

Beginner

Answer

Magic methods are special methods in PHP, always prefixed with a double underscore, that PHP automatically calls in response to certain actions performed on an object, with __construct being called automatically whenever a new object is created to handle initialization logic, and __destruct being called automatically when an object is no longer needed and is about to be removed from memory, letting you run cleanup logic like closing an open file handle.
class Logger {
    public function __construct(private string $filePath) {
        echo "Logger initialized";
    }
    public function __destruct() {
        echo "Logger destroyed";
    }
}
Real-world example A file handling class opens a file resource within its __construct method and reliably closes that same resource within its __destruct method, ensuring proper cleanup happens automatically whenever an instance of that class goes out of scope.

Common follow-ups: When exactly does PHP call the __destruct method during a script's execution?;Can a class have multiple constructors with different parameter signatures?