Complete the code to define a destructor method in a PHP class.
<?php class Sample { public function [1]() { echo "Destructor called"; } } ?>
The destructor method in PHP is named __destruct. It is called when an object is destroyed.
Complete the code to call the destructor automatically when the object is destroyed.
<?php class Logger { public function __destruct() { echo "Closing log file."; } } $log = new Logger(); [1];
Using unset($log) destroys the object and triggers the destructor.
Fix the error in the destructor method name to ensure it is called properly.
<?php class FileHandler { public function [1]() { echo "File closed."; } } ?>
The correct destructor method name is __destruct. Other names will not be called automatically.
Fill both blanks to create a class with a destructor that outputs a message when the object is destroyed.
<?php class UserSession { public function [1]() { echo "Session ended."; } } $session = new UserSession(); [2]($session);
The destructor method is __destruct. Calling unset($session) destroys the object and triggers the destructor.
Fill all three blanks to define a class with a destructor that frees a resource and outputs a message when the object is destroyed.
<?php class DatabaseConnection { private $conn; public function __construct() { $this->conn = "Connected"; } public function [1]() { $this->conn = null; echo [2]; } } $db = new DatabaseConnection(); [3]($db);
The destructor method is __destruct. It frees the connection and prints the message. Using unset($db) destroys the object and calls the destructor.