PHP OOP Destructor

🔥 PHP OOP – Destructor (__destruct())

A destructor is a special method that runs automatically when the object is destroyed.

✅ 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:

Constructor called
Destructor called

(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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *