← Back to Chapters

PHP OOP __wakeup() Method

? PHP OOP __wakeup() Method

? Quick Overview

The __wakeup() magic method in PHP OOP is automatically executed when an object is restored using unserialize(). It is commonly used to reinitialize resources like database connections.

? Key Concepts

  • Triggered during object unserialization
  • Used to restore object state
  • Works alongside __sleep()

? Syntax & Theory

Serialization converts an object into a string for storage. When the object is unserialized, __wakeup() prepares it for use again.

? Code Example

? View Code Example
// PHP class demonstrating __sleep() and __wakeup()
link = "Database Connection Established";
echo $this->link . "
";
}

public function __sleep() {
// Only selected properties are serialized
return ['host','user'];
}

public function __wakeup() {
// Reinitialize resources after unserialization
$this->link = "Database Reconnected";
echo $this->link . "
";
}
}

$conn = new Connection();
$serialized = serialize($conn);
$restored = unserialize($serialized);
?>

? Live Output / Explanation

When the object is unserialized, PHP automatically calls __wakeup(), restoring the database connection message.

? Use Cases

  • Reconnecting database handles
  • Restoring file pointers
  • Reinitializing API clients

? Tips & Best Practices

  • Always reinitialize excluded properties
  • Keep __wakeup() lightweight
  • Avoid restoring sensitive data

? Try It Yourself

  • Create a FileLogger class
  • Exclude file handle using __sleep()
  • Restore file handle in __wakeup()