What is the __destruct() function in PHP?

The __destruct function is a built-in function in PHP that is employed while creating classes.

The __destruct function is called when the object is destructed, or at the exit or stop of a script. This is because by creating a __destruct() function, you tell the PHP parser to automatically call the destructor function at the end of the script.

Note that the destruct function starts with two underscores (__).

In the example below, a __construct() function is automatically called at the creation of an object from the base class, and a __destruct() function is automatically called at the end of the script.

Code

<?php
class sports {
public $name;
public $players;
function __construct($name, $players) {
$this->name = $name;
$this->players = $players;
}
function __destruct() {
echo "The {$this->name} match ends after 90mins of {$this->players} players contest";
}
function get_SportName(){
return $this->name;
}
function get_players(){
return $this->players;
}
}
$soccer = new sports("Soccer", "22");
echo 'This is the sport of '. $soccer -> get_SportName();
echo ' played by 2 teams of ' .$soccer -> get_players().' players in total'.'<br>';
?>

Explanation

In the code snippet above, we use the __construct() function to create a class with a constructor.

We then create the destructor function, which will be called after the script has successfully executed to destruct the object and terminate the script.

Free Resources