Give me some real life examples when you had to use __destruct in your classes
Give me some real life examples when you had to use __destruct in your classes
Certainly! Here's a well-structured response to the interview question about using the __destruct
method in PHP classes:
In my experience as a PHP developer, I've encountered several scenarios where the __destruct
method proved to be invaluable. Here are a few real-life examples:
In one of my projects, I was working on a web application that required frequent database interactions. To ensure that database connections were properly closed and resources were freed, I used the __destruct
method in my database handler class.
class Database {
private $connection;
public function __construct($host, $user, $password, $dbname) {
$this->connection = new mysqli($host, $user, $password, $dbname);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function __destruct() {
if ($this->connection) {
$this->connection->close();
}
}
}
In another project, I had to process large files. To ensure that file handles were properly closed after processing, I implemented the __destruct
method in my file handler class.
class FileHandler {
private $fileHandle;
public function __construct($filePath) {
$this->fileHandle = fopen($filePath, 'r');
if (!$this->fileHandle) {
throw new Exception("Could not open file: $filePath");
}
}
public function __destruct() {
if ($this->fileHandle) {
fclose($this->fileHand...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào