Introduction
In PHP, constructors and destructors are special methods used inside a class. A constructor runs automatically when an object is created, while a destructor runs when an object is destroyed or the script finishes. In this chapter, you will learn how to use __construct() and __destruct() through practical PHP examples. Constructors and Destructors in PHP practice questions with solutions to help you to understand the concepts.
Understanding Constructors and Destructors in PHP
Before starting the practice questions, understand these two special methods.
1. What Is a Constructor in PHP?
A constructor is a special method that runs automatically when you create an object of a class.
PHP uses the __construct() method as a constructor.
Syntax:
public function __construct()
{
// Code to execute when an object is created
}
Example:
<?php
class Student
{
public function __construct()
{
echo "Student object created.";
}
}
$student = new Student();
?>
Output:
Student object created.
When PHP executes $student = new Student();, the constructor runs automatically.
2. What Is a Destructor in PHP?
A destructor is a special method that runs when an object is destroyed or when the script finishes and the object is being cleaned up.
PHP uses the __destruct() method as a destructor.
Syntax:
public function __destruct()
{
// Cleanup code
}
Example:
<?php
class Student
{
public function __construct()
{
echo "Student object created.<br>";
}
public function __destruct()
{
echo "Student object destroyed.";
}
}
$student = new Student();
unset($student);
?>
Output:
Student object created.
Student object destroyed.
The unset() statement removes the variable holding the object. If no other references keep the object alive, its destructor runs.
Constructor vs Destructor
| Constructor | Destructor |
|---|---|
Uses __construct() | Uses __destruct() |
| Runs automatically when an object is created | Runs when an object is destroyed |
| Commonly initializes properties | Commonly performs cleanup |
| Can accept parameters | Cannot accept parameters |
Question 1: Create a Simple Constructor in PHP
Problem Statement
Create a Student class with a constructor that displays a message when an object is created.
PHP Solution
<?php
class Student
{
public function __construct()
{
echo "Welcome! Student object has been created.";
}
}
$student = new Student();
?>
Sample Output
Welcome! Student object has been created.
Explanation
Studentis a class.__construct()is the constructor method.- PHP automatically calls the constructor when an object is created.
$student = new Student();creates the object and triggers the constructor.
You do not need to call __construct() manually.
Concepts Covered
- Constructor in PHP
__construct()method- Automatic method execution
- Object creation
Question 2: Initialize Properties Using a Constructor
Problem Statement
Create an Employee class with name and salary properties. Use a constructor to initialize both properties when an object is created.
PHP Solution
<?php
class Employee
{
public $name;
public $salary;
public function __construct($name, $salary)
{
$this->name = $name;
$this->salary = $salary;
}
public function displayDetails()
{
echo "Employee Name: " . $this->name . "<br>";
echo "Salary: Rs. " . $this->salary;
}
}
$employee = new Employee("Rahul", 35000);
$employee->displayDetails();
?>
Sample Output
Employee Name: Rahul
Salary: Rs. 35000
Explanation
- The constructor accepts two parameters:
$nameand$salary. $this->namestores the received name in the object’s property.$this->salarystores the received salary.- When
new Employee("Rahul", 35000)executes, PHP automatically calls the constructor. - The
displayDetails()method displays the initialized properties.
Important: Constructor parameters provide values to the object during its creation.
Concepts Covered
- Constructor parameters
- Property initialization
$thiskeyword- Automatic constructor execution
Question 3: Create Multiple Objects Using a Constructor
Problem Statement
Create a Product class with productName and price properties. Use a constructor to initialize the properties and create three different product objects.
PHP Solution
<?php
class Product
{
public $productName;
public $price;
public function __construct($productName, $price)
{
$this->productName = $productName;
$this->price = $price;
}
public function displayProduct()
{
echo "Product: " . $this->productName . "<br>";
echo "Price: Rs. " . $this->price . "<br><br>";
}
}
$product1 = new Product("Keyboard", 800);
$product2 = new Product("Mouse", 500);
$product3 = new Product("Monitor", 12000);
$product1->displayProduct();
$product2->displayProduct();
$product3->displayProduct();
?>
Sample Output
Product: Keyboard
Price: Rs. 800
Product: Mouse
Price: Rs. 500
Product: Monitor
Price: Rs. 12000
Explanation
- The constructor accepts the product name and price.
- Three objects are created with different values.
- The constructor runs separately for each object.
- Each object stores its own product information.
- The same
displayProduct()method can display information for all three objects.
Concepts Covered
- Multiple objects
- Constructor with multiple parameters
- Object-specific property values
- Reusing methods
Question 4: Use Default Parameter Values in a Constructor
Problem Statement
Create a Mobile class with brand and model properties. Use a constructor with default parameter values so that an object can be created even when no values are provided.
PHP Solution
<?php
class Mobile
{
public $brand;
public $model;
public function __construct($brand = "Unknown", $model = "Not Available")
{
$this->brand = $brand;
$this->model = $model;
}
public function displayDetails()
{
echo "Brand: " . $this->brand . "<br>";
echo "Model: " . $this->model . "<br><br>";
}
}
$mobile1 = new Mobile("Samsung", "Galaxy S25");
$mobile2 = new Mobile();
$mobile1->displayDetails();
$mobile2->displayDetails();
?>
Sample Output
Brand: Samsung
Model: Galaxy S25
Brand: Unknown
Model: Not Available
Explanation
- The constructor has two parameters with default values.
- The first object receives custom values.
- The second object does not receive any arguments.
- PHP uses the default values for the second object.
- Default parameters make object creation more flexible.
Concepts Covered
- Default constructor parameters
- Optional arguments
- Property initialization
- Creating objects with and without arguments
Question 5: Create a Constructor to Calculate Student Results
Problem Statement
Create a Student class with name, english, maths and science properties. Initialize these properties using a constructor and calculate the total marks and percentage.
Assume each subject carries 100 marks.
PHP Solution
<?php
class Student
{
public $name;
public $english;
public $maths;
public $science;
public function __construct($name, $english, $maths, $science)
{
$this->name = $name;
$this->english = $english;
$this->maths = $maths;
$this->science = $science;
}
public function calculateTotal()
{
return $this->english + $this->maths + $this->science;
}
public function calculatePercentage()
{
return ($this->calculateTotal() / 300) * 100;
}
public function displayResult()
{
echo "Student Name: " . $this->name . "<br>";
echo "Total Marks: " . $this->calculateTotal() . "<br>";
echo "Percentage: " . $this->calculatePercentage() . "%";
}
}
$student = new Student("Priya", 85, 90, 80);
$student->displayResult();
?>
Sample Output
Student Name: Priya
Total Marks: 255
Percentage: 85%
Explanation
- The constructor initializes the student’s name and subject marks.
calculateTotal()adds the marks of all three subjects.calculatePercentage()calculates the percentage using the total marks.displayResult()displays the student’s result.- The constructor makes sure the object receives its initial information when created.
Concepts Covered
- Constructor with multiple parameters
- Initializing multiple properties
- Using constructor values in other methods
- Returning calculated results
Question 6: Create a Simple Destructor in PHP
Problem Statement
Create a Student class with a constructor and destructor. Display a message when the object is created and another message when it is destroyed.
PHP Solution
<?php
class Student
{
public function __construct()
{
echo "Student object created.<br>";
}
public function __destruct()
{
echo "Student object destroyed.";
}
}
$student = new Student();
unset($student);
?>
Sample Output
Student object created.
Student object destroyed.
Explanation
__construct()runs when the object is created.__destruct()runs when the object is destroyed.unset($student)removes the variable holding the object.- If no other references to the object remain, PHP calls the destructor.
Concepts Covered
- Destructor in PHP
__destruct()method- Object destruction
unset()statement
Question 7: Use a Destructor to Display a Cleanup Message
Problem Statement
Create a FileManager class with a constructor and destructor. The constructor should display a message that a file operation has started, and the destructor should display a cleanup message.
PHP Solution
<?php
class FileManager
{
public function __construct()
{
echo "File operation started.<br>";
}
public function __destruct()
{
echo "File operation completed. Cleanup finished.";
}
}
$file = new FileManager();
echo "Working with file...<br>";
unset($file);
?>
Sample Output
File operation started.
Working with file...
File operation completed. Cleanup finished.
Explanation
- The constructor runs when the
FileManagerobject is created. - The next statement displays the working message.
unset($file)removes the object’s variable.- The destructor runs when the object has no remaining references.
- This example demonstrates how a destructor can be used for cleanup-related tasks.
Note: This example only displays messages. It does not actually open or close a file.
Concepts Covered
- Constructor and destructor together
- Object lifecycle
- Cleanup messages
- Explicit object destruction
Question 8: Create Multiple Objects and Observe Destructor Execution
Problem Statement
Create an Employee class with a constructor and destructor. Create two employee objects and destroy them using unset().
PHP Solution
<?php
class Employee
{
public $name;
public function __construct($name)
{
$this->name = $name;
echo $this->name . " object created.<br>";
}
public function __destruct()
{
echo $this->name . " object destroyed.<br>";
}
}
$employee1 = new Employee("Rahul");
$employee2 = new Employee("Priya");
echo "Both employees are working.<br>";
unset($employee1);
echo "First employee object removed.<br>";
unset($employee2);
?>
Sample Output
Rahul object created.
Priya object created.
Both employees are working.
Rahul object destroyed.
First employee object removed.
Priya object destroyed.
Explanation
- Two objects are created using the same class.
- Each constructor receives a different employee name.
- The constructor displays the name of the object being created.
unset($employee1)destroys the first object if no other references exist.unset($employee2)destroys the second object.- Each destructor displays the name stored in its own object.
Concepts Covered
- Multiple object creation
- Constructor and destructor execution
- Object-specific properties
- Destroying objects using
unset()
Question 9: Use a Constructor and Destructor in a Bank Account Class
Problem Statement
Create a BankAccount class with accountHolder and balance properties. Use a constructor to initialize account details and a destructor to display a message when the account object is destroyed.
PHP Solution
<?php
class BankAccount
{
public $accountHolder;
public $balance;
public function __construct($accountHolder, $balance)
{
$this->accountHolder = $accountHolder;
$this->balance = $balance;
echo "Bank account created.<br>";
}
public function deposit($amount)
{
$this->balance = $this->balance + $amount;
}
public function displayBalance()
{
echo "Account Holder: " . $this->accountHolder . "<br>";
echo "Current Balance: Rs. " . $this->balance . "<br>";
}
public function __destruct()
{
echo "Bank account object destroyed.";
}
}
$account = new BankAccount("Amit", 10000);
$account->deposit(5000);
$account->displayBalance();
unset($account);
?>
Sample Output
Bank account created.
Account Holder: Amit
Current Balance: Rs. 15000
Bank account object destroyed.
Explanation
- The constructor initializes the account holder and starting balance.
- The
deposit()method increases the balance. - The
displayBalance()method displays the updated account details. - The destructor displays a message when the object is destroyed.
unset()triggers the destructor if no other references remain.
Concepts Covered
- Constructor-based initialization
- Updating object properties
- Multiple methods in one class
- Destructor execution
- Object lifecycle
Question 10: Create an Employee Management Class Using Constructor and Destructor
Problem Statement
Create an Employee class with the following properties:
- Employee Name
- Employee ID
- Basic Salary
- HRA
- DA
- PF
Use a constructor to initialize all employee details. Create methods to calculate gross salary and net salary. Use a destructor to display a message when the employee object is destroyed.
Salary Formulas:
- Gross Salary = Basic Salary + HRA + DA
- Net Salary = Gross Salary – PF
PHP Solution
<?php
class Employee
{
public $name;
public $employeeId;
public $basicSalary;
public $hra;
public $da;
public $pf;
public function __construct($name, $employeeId, $basicSalary, $hra, $da, $pf)
{
$this->name = $name;
$this->employeeId = $employeeId;
$this->basicSalary = $basicSalary;
$this->hra = $hra;
$this->da = $da;
$this->pf = $pf;
echo "Employee record created.<br><br>";
}
public function calculateGrossSalary()
{
return $this->basicSalary + $this->hra + $this->da;
}
public function calculateNetSalary()
{
return $this->calculateGrossSalary() - $this->pf;
}
public function displayDetails()
{
echo "Employee Name: " . $this->name . "<br>";
echo "Employee ID: " . $this->employeeId . "<br>";
echo "Basic Salary: Rs. " . $this->basicSalary . "<br>";
echo "HRA: Rs. " . $this->hra . "<br>";
echo "DA: Rs. " . $this->da . "<br>";
echo "PF: Rs. " . $this->pf . "<br>";
echo "Gross Salary: Rs. " . $this->calculateGrossSalary() . "<br>";
echo "Net Salary: Rs. " . $this->calculateNetSalary() . "<br>";
}
public function __destruct()
{
echo "Employee record for " . $this->name . " has been closed.";
}
}
$employee = new Employee("Amit", 101, 30000, 6000, 4000, 3000);
$employee->displayDetails();
unset($employee);
?>
Sample Output
Employee record created.
Employee Name: Amit
Employee ID: 101
Basic Salary: Rs. 30000
HRA: Rs. 6000
DA: Rs. 4000
PF: Rs. 3000
Gross Salary: Rs. 40000
Net Salary: Rs. 37000
Employee record for Amit has been closed.
Explanation
- The constructor receives six values and initializes the employee properties.
calculateGrossSalary()adds basic salary, HRA and DA.calculateNetSalary()subtracts PF from gross salary.displayDetails()displays employee information and salary calculations.- The destructor displays a closing message when the object is destroyed.
unset($employee)removes the object’s variable and allows the destructor to run if there are no other references.
Concepts Covered
- Constructor with multiple parameters
- Initializing object properties
- Multiple methods in a class
- Calling one method from another
- Destructor and object cleanup
- Practical object-oriented programming
Key Takeaways
After completing this chapter, you should understand:
- A constructor is a special method that runs automatically when an object is created.
- PHP uses
__construct()to define a constructor. - A constructor can accept parameters.
- Constructors are commonly used to initialize object properties.
- Default parameter values can be used in constructors.
- A destructor is a special method that runs when an object is destroyed.
- PHP uses
__destruct()to define a destructor. unset()can remove an object’s variable and trigger its destructor when no other references remain.- Destructors are commonly used for cleanup tasks.
- A class can contain both a constructor and a destructor.
Frequently Asked Questions (FAQs)
1. What is a constructor in PHP?
A constructor is a special method that executes automatically when an object is created. It is mainly used to initialize object properties.
2. What is the name of the constructor method in PHP?
PHP uses the __construct() method as a constructor.
3. Is it necessary to call the constructor manually?
No. PHP automatically calls the constructor when an object is created using the new keyword.
4. Can a constructor accept parameters in PHP?
Yes. A constructor can accept one or more parameters to receive values during object creation.
5. Can we use default values in constructor parameters?
Yes. You can assign default values to constructor parameters. PHP uses those values when the object is created without the corresponding arguments.
6. What is a destructor in PHP?
A destructor is a special method that runs when an object is destroyed. It is commonly used to perform cleanup tasks.
7. What is the name of the destructor method in PHP?
PHP uses the __destruct() method as a destructor.
8. Does a destructor accept parameters?
No. A PHP destructor cannot accept parameters.
9. When does a destructor execute in PHP?
A destructor executes when an object has no remaining references or when the script finishes and the object is being cleaned up. Its exact execution time can depend on the object’s lifecycle.
10. What is the difference between __construct() and __destruct()?
__construct() runs when an object is created, whereas __destruct() runs when an object is destroyed.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
