PHP | Constructors and Destructors (original) (raw)
Last Updated : 07 Apr, 2025
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.
What are Constructors in PHP?
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:
**Now, let us understand with the help of the example:
PHP `
this−>model=this->model = this−>model=model; this−>color=this->color = this−>color=color; } public function display() { echo "Model: this−>model,Color:this->model, Color: this−>model,Color:this->color"; } } $myCar = new Car("Tesla", "Red"); $myCar->display(); ?>`
Output
Model: Tesla, Color: Red
**In this example:
- The constructor __construct() is used to initialize the properties modelandmodel and modelandcolor when an object of the Car class is created.
- When the object $myCar is created, the constructor is called automatically with “Tesla” and “Red” passed as arguments, thus initializing the car’s properties.
- The display() method is used to print the car details.
What are Destructors in PHP?
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:
**Now, let us understand with the help of the example:
PHP `
this−>connection="Connectedtodatabaseatthis->connection = "Connected to database at this−>connection="Connectedtodatabaseathostname"; echo $this->connection; } // Destructor to close the connection public function __destruct() { echo "\nConnection closed."; } } $db = new Database("localhost"); ?>`
Output
Connected to database at localhost Connection closed.
**In this example:
- The constructor establishes a database connection (a simulated message in this case).
- The destructor is automatically called when the object goes out of scope or when the script finishes executing.
- It cleans up by outputting a message indicating that the connection is closed.
When are Constructors and Destructors Called?
- **Constructors: A constructor is called when you create an object of a class using the new keyword. It is executed automatically during object creation.
$obj = new ClassName(); // Calls __construct()
- **Destructors: A destructor is called when an object is destroyed. It is called automatically when the object is no longer in use.
unset($obj); // Calls __destruct() manually
Constructor and Destructor with Inheritance
When 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:
PHP `
this−>name=this->name = this−>name=name; echo "$this->name is an animal. \n"; } // Destructor in Parent Class public function __destruct() { echo "Animal $this->name is destroyed. \n"; } } class Dog extends Animal { // Constructor in Child Class public function __construct($name) { parent::__construct($name); // Calling Parent Constructor echo "$this->name is a dog. \n"; } // Destructor in Child Class public function __destruct() { echo "$this->name is no longer a dog. \n"; parent::__destruct(); // Calling Parent Destructor } } $dog = new Dog("Rex"); unset($dog); ?>`
Output
Rex is an animal. Rex is a dog. Rex is no longer a dog. Animal Rex is destroyed.
**In this example:
- The parent class, Animal, has its constructor to set the name and display a message.
- The child class Dog calls the parent constructor using parent::__construct($name).
- Both the constructor and destructor of the parent and child classes are executed.
**Best Practices for Constructors and Destructors
Constructors
- Always initialize the properties of the object inside the constructor.
- If you need to pass arguments to the constructor, make sure to document them.
- Constructors should not contain logic that affects program flow (e.g., database queries, heavy processing).
Destructors
- Use destructors to release any resources that your object may have acquired, such as database connections, file handlers, or network connections.
- Avoid using complex logic in destructors, as they are mainly intended for cleanup.
- Destructors should not raise exceptions or output data (unless necessary).
**Constructors vs Destructors
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. |
Conclusion
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.