0
0
PHPprogramming~5 mins

__serialize and __unserialize in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AAn object
BA string
CAn array
DNull
Which method is called automatically when unserializing an object?
A__serialize
B__unserialize
C__wakeup
D__sleep
What is a key advantage of using __serialize over __sleep?
AIt allows returning an array of data instead of just property names
BIt returns a string instead of an array
CIt automatically encrypts data
DIt disables serialization
If you want to exclude a property from serialization, what should you do in __serialize?
AThrow an exception
BInclude it with a null value
CSet it to false
DOmit it from the returned array
What PHP version introduced __serialize and __unserialize?
APHP 7.4
BPHP 8.0
CPHP 5.6
DPHP 7.0
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.