These methods help you control how an object is saved and restored. They let you decide what data to keep when saving an object and how to rebuild it later.
0
0
__serialize and __unserialize in PHP
Introduction
When you want to save an object to a file or send it over the internet.
When you need to customize which parts of an object are saved.
When restoring an object and you want to set up extra things after loading.
When you want to avoid saving sensitive or unnecessary data.
When you want to improve performance by saving only important data.
Syntax
PHP
class ClassName { public function __serialize(): array { // return array of data to save } public function __unserialize(array $data): void { // restore object from $data } }
The __serialize method returns an array of data to save.
The __unserialize method receives that array to rebuild the object.
Examples
This example saves and restores the
name and age properties.PHP
class User { private string $name; private int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } public function __serialize(): array { return ['name' => $this->name, 'age' => $this->age]; } public function __unserialize(array $data): void { $this->name = $data['name']; $this->age = $data['age']; } }
This example saves only the
token and resets secret when restoring.PHP
class Session { private string $token; private string $secret; public function __serialize(): array { // Only save token, not secret return ['token' => $this->token]; } public function __unserialize(array $data): void { $this->token = $data['token']; $this->secret = 'default'; // reset secret } }
Sample Program
This program creates a Product object, saves it as a string, then restores it back to an object and shows its data.
PHP
<?php class Product { private string $name; private float $price; public function __construct(string $name, float $price) { $this->name = $name; $this->price = $price; } public function __serialize(): array { return ['name' => $this->name, 'price' => $this->price]; } public function __unserialize(array $data): void { $this->name = $data['name']; $this->price = $data['price']; } public function display(): void { echo "Product: {$this->name}, Price: \${$this->price}\n"; } } $product = new Product('Book', 12.99); // Serialize the object $serialized = serialize($product); echo "Serialized: $serialized\n"; // Unserialize to new object $newProduct = unserialize($serialized); $newProduct->display();
OutputSuccess
Important Notes
These methods replace older __sleep and __wakeup methods for serialization.
Always return an array from __serialize and accept an array in __unserialize.
Use these methods to avoid saving sensitive data like passwords.
Summary
__serialize controls what data is saved from an object.
__unserialize rebuilds the object from saved data.
They help you save and restore objects safely and efficiently.