Câu hỏi phỏng vấn PHP
Câu hỏi

Give me some real life examples when you had to use __destruct in your classes

Câu trả lời

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:

1. Database Connection Management

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.

php Copy
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();
        }
    }
}

2. File Handling

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.

php Copy
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

junior

Gợi ý câu hỏi phỏng vấn

junior

When should I use require vs include ?

junior

What are the differences between die() and exit() functions in PHP?

junior

What do we mean by keys and values?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào