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

entry

What does $GLOBALS mean?

middle

Differentiate between parameterised and non parameterised functions

middle

What is the difference between using self and $this ?

Bình luận

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

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