__serialize and __unserialize in PHP - Time & Space Complexity
We want to understand how the time to convert an object to a storable form and back grows as the object size changes.
How does the work needed to serialize and unserialize an object change with its data size?
Analyze the time complexity of the following code snippet.
class User {
private array $data;
public function __construct(array $data) {
$this->data = $data;
}
public function __serialize(): array {
return $this->data;
}
public function __unserialize(array $data): void {
$this->data = $data;
}
}
This code converts an object's data array to a simple array for storage and restores it back.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing the data array to copy its elements.
- How many times: Once for each element in the data array during serialization and unserialization.
As the number of items in the data array grows, the time to serialize and unserialize grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The work grows in a straight line with the number of data items.
Time Complexity: O(n)
This means the time to serialize or unserialize grows directly with the size of the data array.
[X] Wrong: "Serialization happens instantly no matter how big the data is."
[OK] Correct: Each element must be processed, so bigger data means more work and more time.
Understanding how serialization time grows helps you write efficient code and explain performance in real projects.
"What if the data array contains nested arrays? How would the time complexity change?"
Practice
__serialize method in a PHP class?Solution
Step 1: Understand serialization
Serialization means saving an object's data so it can be stored or sent.Step 2: Role of __serialize
The__serializemethod tells PHP which properties to save when serializing.Final Answer:
To specify which object properties should be saved during serialization -> Option AQuick Check:
__serialize controls saved data = A [OK]
- Confusing __serialize with __unserialize
- Thinking __serialize rebuilds objects
- Assuming it converts objects to strings automatically
__unserialize method in a PHP class?Solution
Step 1: Check method signature
The__unserializemethod must accept an array parameter and return nothing (void).Step 2: Match correct syntax
public function __unserialize(array $data): void matches the correct signature:public function __unserialize(array $data): void.Final Answer:
public function __unserialize(array $data): void -> Option DQuick Check:
__unserialize signature = B [OK]
- Missing type hint for parameter
- Wrong return type specified
- Using private instead of public visibility
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];
}
public function __unserialize(array $data): void {
$this->name = $data['name'];
$this->age = 0;
}
public function getInfo(): string {
return "Name: {$this->name}, Age: {$this->age}";
}
}
$user = new User('Alice', 30);
$serialized = serialize($user);
$unserialized = unserialize($serialized);
echo $unserialized->getInfo();Solution
Step 1: Analyze __serialize output
The__serializemethod returns only the 'name' property, so 'age' is not saved.Step 2: Analyze __unserialize behavior
When unserializing, 'name' is restored from data, but 'age' is set to 0 explicitly.Final Answer:
Name: Alice, Age: 0 -> Option BQuick Check:
Only 'name' saved, 'age' reset = C [OK]
- Assuming all properties are saved automatically
- Expecting original age to be restored
- Ignoring explicit age reset in __unserialize
__serialize and __unserialize:class Product {
private string $title;
private float $price;
public function __serialize(): array {
return ['title' => $this->title, 'price' => $this->price];
}
public function __unserialize(array $data): void {
$this->title = $data['title'];
$this->price = $data['cost'];
}
}Solution
Step 1: Compare keys in __serialize and __unserialize
The__serializemethod saves 'price' key, but__unserializetries to read 'cost' key.Step 2: Identify mismatch impact
This mismatch causes an undefined index error when unserializing.Final Answer:
Using 'cost' key in __unserialize instead of 'price' -> Option CQuick Check:
Key mismatch in serialize/unserialize = A [OK]
- Using different keys for same property
- Ignoring array keys case sensitivity
- Assuming missing keys won't cause errors
__serialize and __unserialize is best?Solution
Step 1: Understand security needs
Only non-sensitive data should be saved to avoid leaks.Step 2: Use __serialize and __unserialize properly
Return only safe properties in__serializeand restore them in__unserialize, setting sensitive data to safe defaults.Final Answer:
In __serialize, return only non-sensitive properties; in __unserialize, restore those and set sensitive ones to defaults -> Option AQuick Check:
Selective save and safe restore = D [OK]
- Saving all data without filtering
- Assuming encryption happens automatically
- Ignoring sensitive data in unserialize
Ready to prove it?
Pass the test and this pattern moves unknown
