Learn PHP Tutorial

PHP OOP – Destructor


In PHP, destructor method is called when we explicitly destroy an object or when all references to the objects go out of scope. There is no any arguments passed in destructor method. It can not be overloaded. It deallocates memory.

Destructor is start with double underscore (__) followed by destructor keyword (__destructor).

Syntax : __destruct()

Declaration of Destructor

function __destruct()
{
   // initialize the object and its properties by assigning 
   // values
}
<?php
class Car {
  public $name;

  function __construct($name) {
    $this->name = $name;
  }

  function __destruct() {
    echo "The car name is {$this->name}.";
  }
}

$car = new Car("Volkswagen");
?>