PHP Constructor And Destructor

PHP constructor automatically calls whenever a new object is created while the PHP destructor (php __destruct()) function executes automatically when the object is destroyed. The constructor in PHP is called when the object is created.

The magic method __construct() is known as a constructor that is automatically called whenever a new object is created.

Please keep in mind that the construct function starts with two underscores (__).

The __construct() method should always have public visibility.

When you don't have a constructor (or you have a constructor without arguments), you can create the object from the class without parentheses.

    
    class House{}
    $house = new House;//object
   

Source Code

          <?php
class Fruit {
  public $name;
  public $color;

  function __construct($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
        
Try it now

But, if you have a constructor with arguments, you should send the values for those arguments when you create them.

Source Code

          <?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->name;
  }
  function get_color() {
    return $this->color;
  }
}

$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
        
Try it now

PHP Destructor Function

The destructor in php (__destruct()) is executed automatically when the object is destroyed. Keep in mind that the destructor function starts with two underscores (__).

Source Code

          <?php
class House {
	public $name;
	public $color;
	public function __construct($name, $color) {
		$this -> name = $name;
		$this -> color = $color;
	}
	public function __destruct() {
		echo "The color of the {$this -> name} is {$this -> color}";
	}
}
$blackHouse = new House("John's House", "black");
?>
        
Try it now

In the above example, the __destruct() method will be called at the end of the execution of the script.

Conclusion

I hope that you have understood the PHP class constructor as well as the PHP class destructor. Basically, it comes into action when a new object is created or destroyed, respectively. It is widely used during web development. Therefore, you must understand the constructor and the destructor.

Web Tutorials

PHP Constructor And Destructor
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4