The __sleep() magic method is automatically triggered when an object is serialized using serialize(). It allows developers to control which object properties are stored.
__wakeup()The __sleep() method is useful when objects contain resources like database connections that should not be serialized.
// Demonstrates how __sleep controls object serialization
<?php
class User {
public $name;
public $email;
private $dbConnection;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
$this->dbConnection = "DB Connection Resource";
}
public function __sleep() {
// Only serialize safe properties
return ['name', 'email'];
}
}
$user = new User("Meghraj", "meghraj@example.com");
$serializedUser = serialize($user);
echo $serializedUser;
?>
The serialized string includes only name and email. The database connection is excluded, preventing errors and reducing data size.
__wakeup() if resources need restorationSession class with userId, token, and dbHandle__sleep() to serialize only safe properties__wakeup()