Object Serialization in PHP: From Basics to Advanced Techniques
Serialization is the process of converting complex data structures (objects, arrays) into a linear format suitable for storage or transmission. In PHP, this mechanism is especially important for preserving object state between requests, transmitting data via API, or writing to databases. In this article, we will thoroughly examine all aspects of serialization in PHP.
What is Serialization and Why is it Needed?
Serialization allows you to "freeze" an object into a string, and then restore it back. This is useful in the following scenarios:
- Saving user sessions (PHP automatically serializes session data)
- Caching complex objects in Redis or Memcached
- Transferring objects between microservices
- Storing configurations in files
- Debugging and logging object state
Basic Serialization: serialize() and unserialize()
PHP provides two main functions for working with 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 Petrov', 'ivan@example.com', 'secret123');$serialized = serialize($user);echo $serialized;// Output: O:4:"User":3:{s:4:"name";s:11:"Ivan Petrov";s:5:"email";s:16:"ivan@example.com";s:14:"\\0User\\0password";s:9:"secret123";}
// Restoring the object$unserialized = unserialize($serialized);echo $unserialized->name; // Ivan Petrov?>Important: The serialize() function processes all properties of the object, including private and protected ones. Private properties are encoded with the prefix \\0ClassName\\0, protected ones — \\0*\\0.
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.
- __wakeup() — called after deserialization. Used to reinitialize resources (e.g., database connections).
<?phpclass DatabaseConnection { private $connection; private $dsn; private $username; private $password; private $cache = [];
public function __construct($dsn, $username, $password) { $this->dsn = $dsn; $this->username = $username; $this->password = $password; $this->connect(); }
private function connect() { // Simulating a database connection $this->connection = new stdClass(); $this->connection->connected = true; }
public function __sleep() { // Do not serialize the connection resource and password return ['dsn', 'username', 'cache']; }
public function __wakeup() { // Restore the connection after deserialization $this->connect(); }}
$db = new DatabaseConnection('mysql:host=localhost;dbname=test', 'root', 'pass');$serialized = serialize($db);$restored = unserialize($serialized);?>JSON Serialization: json_encode() and json_decode()
JSON is a more universal format supported by many programming languages. In PHP, the functions json_encode() and json_decode() are used for JSON serialization.
<?phpclass Product { public $id; public $name; public $price;
public function __construct($id, $name, $price) { $this->id = $id; $this->name = $name; $this->price = $price; }}
$product Also in library
Logging in Java: Overview of Best Libraries and Solutions
Authorization and Authentication in PHP: A Complete Guide with Examples
Reactive Programming in Swift: Combine and RxSwift for iOS/macOS
Node.js Application Configuration: Best Tools and Approaches
JWT Tokens in Go (Golang): golang-jwt Library and Usage Examples