Recall & Review
beginner
What is the purpose of the
__serialize magic method in PHP?The
__serialize method allows an object to specify how it should be converted into an array for serialization. It returns an array of the object's data to be saved.Click to reveal answer
beginner
What does the
__unserialize magic method do in PHP?The
__unserialize method receives an array of data and restores the object's properties from it when unserializing.Click to reveal answer
intermediate
How do
__serialize and __unserialize improve over older serialization methods?They provide a clear, explicit way to control what data is saved and restored, improving security and flexibility compared to
__sleep and __wakeup.Click to reveal answer
beginner
Show a simple example of a class implementing <code>__serialize</code> and <code>__unserialize</code>.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'];
}
}Click to reveal answer
intermediate
Why might you want to customize serialization with
__serialize and __unserialize?To control exactly which properties are saved, avoid saving sensitive data, or transform data before saving and after loading.
Click to reveal answer
What type of value must
__serialize return?✗ Incorrect
__serialize must return an array representing the object's data.Which method is called automatically when unserializing an object?
✗ Incorrect
__unserialize is called to restore the object's state from an array.What is a key advantage of using
__serialize over __sleep?✗ Incorrect
__serialize returns an array of data, giving more control than __sleep which returns property names.If you want to exclude a property from serialization, what should you do in
__serialize?✗ Incorrect
Simply omit the property from the array returned by
__serialize to exclude it.What PHP version introduced
__serialize and __unserialize?✗ Incorrect
__serialize and __unserialize were introduced in PHP 7.4.Explain how
__serialize and __unserialize work together to save and restore an object's state.Think about saving and loading data as a two-step process.
You got /4 concepts.
Describe a situation where customizing serialization with
__serialize and __unserialize is useful.Consider privacy or data format needs.
You got /4 concepts.