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.
__sleep()Serialization converts an object into a string for storage. When the object is unserialized, __wakeup() prepares it for use again.
// 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);
?>
When the object is unserialized, PHP automatically calls __wakeup(), restoring the database connection message.
__wakeup() lightweight__sleep()__wakeup()