In PHP, constructors and destructors are special methods that manage an object's lifecycle.
- Constructor: Initializes an object when it is created.
- Destructor: Performs cleanup when an object is destroyed or the script terminates.
Constructors
A constructor is a special method named __construct() that runs when an object is created. It is commonly used to initialize properties and set the initial state of an object.
Example: Initializes object using Constructor
<?php
class Car {
public $model;
public $color;
public function __construct($model, $color) {
$this->model = $model;
$this->color = $color;
}
public function display() {
echo "Model: $this->model, Color: $this->color";
}
}
$myCar = new Car("Tesla", "Red");
$myCar->display();
?>
- __construct() initializes the $model and $color properties.
- new Car("Tesla", "Red") creates an object and passes arguments to the constructor.
- display() prints the initialized property values.
Syntax:
$objectName = new ClassName();Destructors
A destructor is a special method named __destruct() that runs when an object is destroyed or during script shutdown. It can be used for cleanup tasks, such as releasing resources owned by an object.
Example: Demonstrates when a destructor is called.
<?php
class Database {
public function __construct($hostname) {
echo "Connected to database at $hostname\n";
}
public function __destruct() {
echo "Cleanup completed.";
}
}
$db = new Database("localhost");
unset($db);
?>
- The constructor displays a message when the object is created.
- unset($db) removes the variable reference to the object.
- Because no other references remain, the object is destroyed and its destructor runs.
Syntax:
class ClassName {
public function __destruct() {
// Cleanup code
}
}
Note: This example simulates a connection using messages; it does not establish or close an actual database connection.
Constructors and Destructors During the Object Lifecycle
- Constructor: Runs when an object is instantiated using new.
- Destructor: Runs when an object is destroyed, typically when no references remain, or during script shutdown.
- unset(): Removes a variable or reference. The destructor runs at that point only if the object is no longer referenced elsewhere.
- Script termination: PHP generally invokes destructors for remaining objects during shutdown, although cleanup order and timing can depend on object references and shutdown behavior.
Constructors and Destructors in Inheritance
When a child class defines its own constructor, PHP does not automatically call the parent constructor. The child constructor must explicitly call parent::__construct() when parent initialization is required.
Similarly, if a child class overrides the parent destructor, it must call parent::__destruct() if the parent's cleanup logic must also run.
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
echo "$this->name is an animal.\n";
}
public function __destruct() {
echo "Animal $this->name is destroyed.\n";
}
}
class Dog extends Animal {
public function __construct($name) {
parent::__construct($name);
echo "$this->name is a dog.\n";
}
public function __destruct() {
echo "$this->name is no longer a dog.\n";
parent::__destruct();
}
}
$dog = new Dog("Rex");
unset($dog);
?>
- Dog extends the Animal class.
- parent::__construct($name) invokes the parent constructor to initialize the inherited property.
- The child destructor runs first and then explicitly invokes the parent destructor.
- unset($dog) triggers destruction because no other references to the object remain.
Best Practices for Constructors and Destructors
Constructors:
- Initialize required properties when an object is created.
- Validate constructor arguments where necessary.
- Avoid unnecessarily expensive operations during object creation.
- Use property types where they improve clarity and reliability.
Destructors:
- Use destructors for appropriate cleanup of resources owned by an object.
- Avoid relying on destructors for critical application logic or guaranteed execution at a particular time.
- Avoid throwing exceptions from destructors.
- Close resources explicitly when predictable cleanup is important.
Constructors vs. Destructors
| Constructor | Destructor |
|---|---|
| Uses the __construct() method. | Uses the __destruct() method. |
| Initializes an object. | Performs cleanup tasks. |
| Can accept arguments. | Cannot accept arguments. |
| Called when an object is created. | Called when an object is destroyed or during script shutdown. |
| The parent constructor must be called explicitly if needed. | The parent destructor must be called explicitly if the child overrides it and parent cleanup is required. |