![]() |
VOOZH | about |
In PHP, constructors and destructors are special methods that are used in object-oriented programming (OOP). They help initialize objects when they are created and clean up resources when the object is no longer needed. These methods are part of the class lifecycle.
In this article, we will discuss what constructors and destructors are and how to use them.
A constructor is a special function or method in a class that is automatically called when an object of the class is created. The constructor is mainly used for initializing the object, i.e., setting the initial state of the object by assigning values to properties.
Syntax:
<?php
class ClassName {
public function __construct() {
// Constructor code here
}
}
?>Now, let us understand with the help of the example:
Model: Tesla, Color: Red
In this example:
A destructor is a special method in PHP that is automatically called when an object is destroyed or goes out of scope. It is mainly used for cleaning up or releasing resources that the object might have acquired during its lifetime, such as closing file handles or database connections.
Syntax:
<?php
class ClassName {
public function __destruct() {
// Destructor code here
}
}
?>Now, let us understand with the help of the example:
Connected to database at localhost Connection closed.
In this example:
$obj = new ClassName(); // Calls __construct()unset($obj); // Calls __destruct() manuallyWhen a class extends another class, the constructor of the parent class is not automatically called. However, the destructor of the parent class is automatically called when the child class is destroyed.
Now, let us understand with the help of the example:
Rex is an animal. Rex is a dog. Rex is no longer a dog. Animal Rex is destroyed.
In this example:
| Constructors | Destructors |
|---|---|
| Accepts one or more arguments. | No arguments are passed. It's void. |
| Has the same name as the class. | Has the same name as the class, with a tilde (~) prefix. |
| Used to initialize the instance of a class. | Used to de-initialize objects to free up memory. |
| Constructors can be overloaded. | Destructors cannot be overloaded. |
| It is called at the time the object is created. | It is called automatically at the time of object deletion. |
| Allocates memory. | It deallocates memory. |
| Multiple constructors can exist in a class. | Only one Destructor can exist in a class. |
Constructors and Destructor methods are very useful as they make very c tasks easier during coding. These encourage re-usability of code without unnecessary repetition. Both of them are implicitly called by the compiler, even though they are not defined in the class.