PHP Destructors | Destroy a Class Object

Destructors are inverse of Constructors in Object Oriented Programming. They are automatically called when an object is no longer in scope. In this article, we will discuss about PHP Destructors.

If you are new to Object Oriented Programming in PHP, you should first read the Introduction article.

Class Destructors

A destructor is a special method which gets automatically called when an object is no longer needed or is no longer in scope. They are not explicitly called and are invoked as soon as the object is destroyed.

Also, like constructors, it is not mandatory to define destructors in PHP. You need to create them only if you want to perform a specific operation while destroying an object.

It is not mandatory to define a destructor as they are automatically called when an object is destroyed.

Example

<?php 
  
	class Test {

		public function __construct() {
			echo 'Object Created';
		}

		public function __destruct() {
			echo 'Object Destroyed';
		}

	}

	$testObject = new Test();
	  
?> 

In the above example, the class Test has a constructor and a destructor function. When we create an object it invokes the constructor of the class. After the script is over, the object is no longer in scope and the destructor is automatically called.

OUTPUT:
Object Created 
Object Destroyed

Conclusion

In this article, we discussed PHP Destructors. You can read more about it on the Official PHP Documentation. Additionally, you can learn Object Oriented Concepts in PHP on Concatly.

Spread the Knowledge

Leave a Reply

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