Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is the __destruct() function in PHP?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring