__destruct 메서드

__destruct 함수는 PHP의 매직 메서드로, 객체가 메모리에서 삭제될 때 자동으로 호출됩니다. 이는 스크립트 실행이 종료되거나 객체가 명시적으로 파괴될 때 발생합니다. 이 메서드는 리소스(예: 파일 디스크립터나 DB 연결 닫기)를 해제하는 데 유용합니다.

구문

phpclass MyClass {
  public function __destruct() {
    // 소멸자 코드
  }
}

예제

객체가 소멸될 때 메시지를 출력하는 소멸자가 있는 간단한 클래스 예제:

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

$obj = new Test();
unset($obj); // 소멸자를 호출함
?>

코드 실행 결과:

php'Object destroyed'

예제

리소스 해제 예제 (파일 닫기):

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');
// 파일 작업...
unset($handler); // 파일을 자동으로 닫음
?>

코드 실행 결과:

php'File closed'

함께 보기