PHP Constructor And Destructor

Constructor & Destructor in Php

PHP Constructor And Destructor : PHP provides the constructor magic method __construct(), which is called automatically whenever a new object is instantiated.

Example :
class Person {

  public function __construct() {

    echo "Object created";

  }

}

$p = new Person();

The __construct() method is often used for any initialization that the object may need before it is used.

Example :
                    class Person {

  public $name;

  public $age;

  public function __construct($name, $age) {

    $this->name = $name;

    $this->age = $age;

  }

}

$p = new Person("David", 42);

PHP Class Destructor

Similar to the class constructor, there is a destructor magic method __destruct(), which is automatically called when an object is destroyed.

Example :
  class Person {

  public function __destruct() {

    echo "Object destroyed";

  }

}

$p = new Person();

This script creates a new Person object. When the script ends the object is automatically destroyed, which calls the destructor and outputs the message “Object destroyed”. To explicitly trigger the destructor, you can destroy the object using the unset() function in a statement similar to: unset($p);


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *