__destruct metodi

__destruct funksiýasy PHP-däki bir sÿhyrly metoddur, ol obýektiň ýatdan çykarylmagy bilen awtomatik çagyrylýar. Bu ýagdaý ýa skript işini tamamlanynda, ýa-da obýektiň açyk-aydyn ýok edilmegi bilen bolýar. Bu metod resurslary boşatmak üçin (meselem, faýl deskriptorlaryny ýa-da BD birikmelerini ýapmak) peýdaly.

Sintaksis

phpclass MyClass {
  public function __destruct() {
    // destruktoryň kody
  }
}

Mysal

Obýektiň ýok edilmegi bilen habary çap edýän destruktory bar bolan ýönekeý klas:

php<?php
class Test {
  public function __destruct() {
    echo 'Object destroyed';
  }
}

$obj = new Test();
unset($obj); // Destruktory çagyrar
?>

Kodyň ýerine ýetiriliş netijesi:

php'Object destroyed'

Mysal

Resurslary boşatmak bilen mysal (faýly ýapmak):

php<?php
class FileHandler {
  private $file;

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

  public function __destruct() {
    if ($this->file) {
      fclose($this->file);
      echo 'File closed';
    }
  }
}

$handler = new FileHandler('example.txt');
// Faýl bilen iş...
unset($handler); // Faýly awtomatik ýapar
?>

Kodyň ýerine ýetiriliş netijesi:

php'File closed'

Şeýle-de garaň