PHP Object Serialization with __sleep and __wakeup

In PHP, object serialization converts an object into a storable string representation, while unserialization restores it. The __sleep() and __wakeup() magic methods act as hooks during these processes, allowing developers to clean up resources, commit pending data, or re-establish database connections. This article explains how these two magic methods control object serialization and unserialization with clear explanations and practical code examples.

Understanding the __sleep() Method

The __sleep() magic method is automatically triggered when you call serialize() on an object. Its primary purpose is to prepare the object for serialization by cleaning up resources (such as closing database connections or file pointers) and defining which object properties should be saved.

To control the serialization, __sleep() must return an indexed array containing the names of the properties that you want to serialize. Any properties not included in this array will be omitted from the serialized string.

class DatabaseSession {
    private $connection;
    public $username;
    public $sessionId;

    public function __construct($username, $sessionId) {
        $this->username = $username;
        $this->sessionId = $sessionId;
        $this->connect();
    }

    private function connect() {
        // Simulating a database connection resource
        $this->connection = "Active Connection Resource";
    }

    public function __sleep() {
        // Close connections or clean up resources here
        $this->connection = null;

        // Return only the properties that need to be serialized
        return ['username', 'sessionId'];
    }
}

In this example, the $connection property (which represents an active resource) is excluded from serialization because resources cannot be reliably serialized.

Understanding the __wakeup() Method

Conversely, the __wakeup() magic method is executed automatically when unserialize() is called on a serialized string. Its main purpose is to re-establish any resources, database connections, or state variables that were lost or omitted during the serialization process.

Unlike __sleep(), the __wakeup() method does not return any value. Instead, it directly restores the internal state of the newly re-created object.

class DatabaseSession {
    private $connection;
    public $username;
    public $sessionId;

    // ... (previous __construct and __sleep methods) ...

    public function __wakeup() {
        // Re-establish the database connection upon unserialization
        $this->connect();
    }

    private function connect() {
        $this->connection = "Active Connection Resource";
    }
}

When the object is unserialized, PHP recreates the object using the serialized properties (username and sessionId) and then calls __wakeup(), which restores the $connection resource.

Important Considerations and PHP 7.4+ Alternatives

While __sleep() and __wakeup() are widely supported and still used, they have some limitations. For example, __sleep() cannot return private properties of parent classes easily.

To address these limitations, PHP 7.4 introduced the __serialize() and __unserialize() magic methods. These newer methods return and accept an associative array representing the complete state of the object, offering more flexibility and control than the traditional __sleep() and __wakeup() methods. However, if your codebase requires compatibility with older PHP versions, __sleep() and __wakeup() remain the standard tools for managing object serialization.