PHP out of the box provides us few magic methods. Constructor and destructor are the important magic methods. So when we create a class object (Initialize a class). It Constructor function fires automatically. Now when we delete the variable where we stored the class object refrence then destructor function fires.
Have a look on this code
class Test
{
public $name = 'Marcus ';
public $statement = ' Object Died';
//Constructor method
public function __construct()
{
echo $this->displayName();
}
//custom method
public function displayName()
{
return $this->name;
}
// Destructor method
public function __destruct()
{
echo $this->statement;
}
}
$test = new Test();
unset($test);
Now when we create object here
$test = new Test();
This line of code fires the construct method. After that we are using “Unset” function from PHP. to delete the “$test” variable. This is when destruct will fire.
You must log in to post a comment.