PHP OOP Destructor

PHP Tutorial

 PHP OOP Destructor (__destruct())

PHP OOP 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

FeatureConstructorDestructor
RunsWhen object is createdWhen object is destroyed
Name__construct()__destruct()
UseInitializeCleanup
Called automatically Yes Yes

You may also like...