PHP OOP Destructor
🔥 PHP OOP – Destructor (__destruct())
✅ 1. Destructor Syntax
🟩 2. When Does Destructor Run?
A destructor runs automatically when:
✔ The script ends
✔ The object goes out of scope
✔ You unset() the object
✔ PHP decides object is no longer needed
🟦 3. Simple Destructor Example
Output:
(Destructor runs last.)
🟧 4. Destructor Running After unset()
🟥 5. Real-Life Use Case of Destructor
Example: Closing Database Connection Automatically
Destructor makes sure connection closes even if you forget.
🟨 6. Destructor in a Class with Multiple Objects
Each object has its own destructor.
🎯 Key Differences: Constructor vs Destructor
| Feature | Constructor | Destructor |
|---|---|---|
| Runs | When object is created | When object is destroyed |
| Name | __construct() |
__destruct() |
| Use | Initialize | Cleanup |
| Called automatically | ✔ Yes | ✔ Yes |
