The __wakeup Method

The __wakeup method is a magic method in PHP, which is automatically called during object deserialization. It allows restoring the object's resources or performing additional actions after deserialization.

Syntax

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

Example

An example of a class with the __wakeup method that restores the database connection:

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);
?>

Example

An example of restoring temporary files after deserialization:

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);
?>

See Also

  • the __sleep method,
    which is called before object serialization
  • the __construct method,
    which is called when an object is created