__wakeup 메서드

__wakeup 메서드는 PHP의 매직 메서드로, 객체 역직렬화 시 자동으로 호출됩니다. 이 메서드는 객체의 리소스를 복원하거나 역직렬화 후 추가 작업을 수행할 수 있게 해줍니다.

구문

phppublic function __wakeup(): void
{
  // code
}

예시

__wakeup 메서드를 사용하여 데이터베이스 연결을 복원하는 클래스 예시:

php<?php
  class DatabaseConnection
  {
    private $connection;
    
    public function __construct()
    {
      $this->connect();
    }
    
    private function connect()
    {
      $this->connection = 'db_connected';
    }
    
    public function __sleep()
    {
      return [];
    }
    
    public function __wakeup()
    {
      $this->connect();
    }
  }
  
  $db = new DatabaseConnection();
  $serialized = serialize($db);
  $unserialized = unserialize($serialized);
?>

예시

역직렬화 후 임시 파일을 복원하는 예시:

php<?php
  class TempFileHandler
  {
    private $tempFiles = [];
    
    public function addTempFile($file)
    {
      $this->tempFiles[] = $file;
    }
    
    public function __wakeup()
    {
      foreach ($this->tempFiles as $file) {
        if (file_exists($file)) {
          unlink($file);
        }
      }
      $this->tempFiles = [];
    }
  }
  
  $handler = new TempFileHandler();
  $handler->addTempFile('temp1.txt');
  $serialized = serialize($handler);
  $unserialized = unserialize($serialized);
?>

함께 보기

  • __sleep 메서드,
    객체 직렬화 전에 호출됨
  • __construct 메서드,
    객체 생성 시 호출됨