B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP PHP Constructor and Destructor | LiveCodeProgramming

PHP Constructor and Destructor

A constructor is a special method that runs automatically when an object is created. A destructor is called automatically when the object is destroyed (or script ends).

Constructor एक विशेष method होता है जो object बनते ही अपने आप चल जाता है। Destructor तब चलता है जब object destroy हो जाता है या स्क्रिप्ट खत्म होती है।

Example using Employee class

This example creates an Employee object using a constructor and displays a message from the destructor at the end.

इस उदाहरण में एक Employee object constructor से बनाया गया है और स्क्रिप्ट के अंत में destructor से एक message दिखाया गया है।

<?php
class Employee {
  public $name;
  public $age;
  public $salary;

  // Constructor
  public function __construct($name, $age, $salary) {
    $this->name = $name;
    $this->age = $age;
    $this->salary = $salary;
    echo "Constructor called: Employee created.\n";
  }

  // Destructor
  public function __destruct() {
    echo "Destructor called: Employee object destroyed.";
  }

  public function displayInfo() {
    echo "Name: {$this->name}\n";
    echo "Age: {$this->age}\n";
    echo "Salary: ₹{$this->salary}\n";
  }
}

$emp = new Employee("Amit", 28, 60000);
$emp->displayInfo();
?>
Constructor called: Employee created. Name: Amit Age: 28 Salary: ₹60000 Destructor called: Employee object destroyed.