ADVERTISEMENT
ADVERTISEMENT

Constructor and Destructor in PHP 

In PHP, constructors and destructors are special functions in a class. Constructors and destructors in PHP are special methods used in object-oriented programming. A constructor initializes an object when it’s created, while a destructor cleans up resources when the object is no longer needed. Understand the difference between Constructors and Destructors in PHP.

What is a Constructor?

A constructor in PHP is a special method that runs automatically when an object is created. It initializes properties and sets up the object. Constructors use the __construct() function and help reduce repetitive code.You use it to:

  • Set initial values for properties.
  • Perform setup tasks when the object starts.

Syntax:

public function __construct() 
{
    // Code to run when object is created
}

Example:

<?php
class Student 
{
    public $name;

    // Constructor
    public function __construct($name) {
        $this->name = $name;  // Set the name property
        echo "Student $name is created! <br>";
    }
}

// Create an object
$student1 = new Student("Raj");
// Output: Student Raj is created!
?>

Explanation:

  • __construct($name) runs automatically when $student1 is created.
  • It sets the $name property and prints a message.

What is a Destructor?

A destructor is a special method that runs automatically when an object is destroyed (script ends or object is unset). It’s used to:

  • Clean up resources.
  • Close files or database connections.

Syntax: 

public function __destruct()
 {
    // Code to run when object is destroyed
}

Example:

<?php
class Student 
{
    public $name;

    // Constructor
    public function __construct($name) 
    {
        $this->name = $name;
        echo "Student $name is created!<br>";
    }

    // Destructor
    public function __destruct()
    {
        echo "Student $this->name is removed!<br>";
    }
}

// Create an object
$student1 = new Student("Raj");
// Destructor runs automatically at the end
?>

Output:

Student Raj is created!

 Student Raj is removed! 

Explanation:

  • The constructor runs when $student1 is created.
  • The destructor runs automatically when the script ends.

Difference Between Constructor and Destructor in PHP 

Feature Constructor Destructor
Purpose Initializes an object when it is created. Cleans up resources when the object is destroyed.
Method Name __construct() __destruct()
When it Runs Automatically runs when an object is created. Automatically runs when the object is destroyed.
Usage Set initial values, open files, or connect to databases. Close files, release memory, or end connections.
Parameters Can accept parameters to initialize properties. Does not take any parameters.
Frequency Can be called multiple times (by creating new objects). Called only once at the end of an object’s life.

 


ADVERTISEMENT

ADVERTISEMENT