เมธอด __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,
    ซึ่งถูกเรียกเมื่อสร้างอ็อบเจ็กต์