Sobes.tech
Junior — Middle

Share your experience of using destructors in your projects.

sobes.tech AI

Answer from AI

In PHP, destructors are __destruct() methods that are called when an object is destroyed, for example, when the object goes out of scope or the script terminates.

I used destructors to release resources, such as closing database connections or writing logs when the object finishes its work.

Example of using a destructor:

class FileLogger {
    private $fileHandle;

    public function __construct($filename) {
        $this->fileHandle = fopen($filename, 'a');
    }

    public function log($message) {
        fwrite($this->fileHandle, $message . "\n");
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}

$logger = new FileLogger('app.log');
$logger->log('Start of work');
// When the script ends or $logger is destroyed, the file will automatically close

It is important to remember that the order of destructor calls is not always guaranteed, so they should not be relied upon for critical operations.