Object Serialization in PHP: A Complete Guide
Serialization is the process of converting complex data structures (objects, arrays) into a string or binary format that can be saved to a file, transmitted over a network, or cached. In PHP, this mechanism is implemented using the built-in functions serialize() and unserialize(). In this article, we will take a detailed look at how object serialization works, what pitfalls exist, and how to use magic methods for fine-tuning the process.
Basic Serialization Functions
PHP provides two key functions for working with serialization:
serialize($value)— converts a value (except resources) into a string suitable for storage. For objects, the class name and all properties (including private and protected ones) are preserved.unserialize($string)— restores the original value from a string. For objects, the class constructor is automatically called (if defined) and the saved properties are applied.
Simple Example of Object Serialization
Consider a basic User class and its serialization:
<?phpclass User { public $name; public $email; private $password;
public function __construct($name, $email, $password) { $this->name = $name; $this->email = $email; $this->password = $password; }}
$user = new User('Ivan', 'ivan@example.com', 'secret123');$serialized = serialize($user);echo $serialized;// Output: O:4:"User":3:{s:4:"name";s:8:"Ivan";s:5:"email";s:16:"ivan@example.com";s:12:"\\0User\\0password";s:9:"secret123";}?>Note: The private property $password appears in the string as \\0User\\0password — this is a special notation for private fields, where \\0 is a null byte.
Restoring an Object from a Serialized String
<?php$serialized = 'O:4:"User":3:{s:4:"name";s:8:"Ivan";s:5:"email";s:16:"ivan@example.com";s:12:"\\0User\\0password";s:9:"secret123";}';$user = unserialize($serialized);echo $user->name; // Ivanecho $user->email; // ivan@example.com// The private password property is also restored but is not directly accessible?>Important: During deserialization, PHP tries to load the class if it is not already defined. If the class does not exist, an instance of the built-in class __PHP_Incomplete_Class will be created.
Magic Methods __sleep() and __wakeup()
To control the serialization process, PHP provides two magic methods:
__sleep()— called before serialization. It should return an array of property names to be serialized. Useful for closing database connections, releasing resources, or hiding confidential data.__wakeup()— called immediately after deserialization. Used to reconnect to a database, restore resources, or verify data integrity.
Example with __sleep() and __wakeup()
<?phpclass DatabaseConnection { private $host; private $user; private $password; private $connection;
public function __construct($host, $user, $password) { $this->host = $host; $this->user = $user; $this->password = $password; $this->connect(); }
private function connect() { // Emulate connection $this->connection = "Connection resource to {$this->host}"; }
public function __sleep() { // Do not serialize the connection resource, only the data for reconnection return ['host', 'user', 'password']; }
public function __wakeup() { // Restore Also in library
Parsing HTML in Rust: Libraries and Examples for Web Scraping
Sending SMS in Java: Overview and Examples of Using API Libraries (Twilio, Nexmo)
Data Validation in Swift (iOS/macOS): Libraries and Approaches
Monitoring PHP Applications with php-ast and xhprof Libraries