Bird
Raised Fist0
PHPprogramming~20 mins

__serialize and __unserialize in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Serialization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of __serialize method in PHP
What is the output of the following PHP code when serialized?
PHP
<?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];
    }
}

$user = new User('Alice', 30);
print_r($user->__serialize());
AArray ( [name] => Alice [age] => 30 )
BArray ( [0] => Alice [1] => 30 )
CArray ( [name] => Alice )
DArray ( [age] => 30 )
Attempts:
2 left
💡 Hint
The __serialize method returns an associative array with keys and values representing the object's data.
❓ Predict Output
intermediate
2:00remaining
Output of __unserialize method in PHP
What will be the output of the following PHP code?
PHP
<?php
class Product {
    public string $title;
    public float $price;

    public function __unserialize(array $data): void {
        $this->title = $data['title'];
        $this->price = $data['price'];
    }
}

$data = ['title' => 'Book', 'price' => 12.5];
$product = new Product();
$product->__unserialize($data);
echo $product->title . ' costs $' . $product->price;
AUndefined property: Product::$title
BBook costs $0
CBook costs $12.5
DFatal error: Unserialize failed
Attempts:
2 left
💡 Hint
The __unserialize method sets object properties from the given array.
🔧 Debug
advanced
2:00remaining
Identify the error in __serialize implementation
What error will this PHP code produce when trying to serialize the object?
PHP
<?php
class Person {
    private string $name;
    private int $age;

    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function __serialize(): array {
        return json_encode(['name' => $this->name, 'age' => $this->age]);
    }
}

$person = new Person('Bob', 25);
serialize($person);
ANo error, serialization works fine
BTypeError: Return value of __serialize() must be of the type array, string returned
CWarning: json_encode() expects parameter 1 to be array, string given
DFatal error: Cannot serialize private properties
Attempts:
2 left
💡 Hint
Check the return type of __serialize method.
📝 Syntax
advanced
2:00remaining
Which __unserialize method is syntactically correct?
Which option shows a syntactically correct __unserialize method in PHP?
A
public function __unserialize(array $data): void {
    $this-&gt;name = $data['name'];
    $this-&gt;age = $data['age'];
}
B
public function __unserialize($data) {
    $this-&gt;name = $data['name'];
    $this-&gt;age = $data['age'];
}
C
public function __unserialize(array $data) {
    $this-&gt;name = $data['name'];
    $this-&gt;age = $data['age'];
}
D
public function __unserialize(array $data): string {
    $this-&gt;name = $data['name'];
    $this-&gt;age = $data['age'];
    return 'done';
}
Attempts:
2 left
💡 Hint
Check the method signature and return type for __unserialize.
🚀 Application
expert
2:00remaining
How many items in serialized data after __serialize?
Given this PHP class, how many key-value pairs will the __serialize method return?
PHP
<?php
class Session {
    private string $id;
    private array $data;
    private bool $active;

    public function __construct(string $id, array $data, bool $active) {
        $this->id = $id;
        $this->data = $data;
        $this->active = $active;
    }

    public function __serialize(): array {
        return [
            'id' => $this->id,
            'data' => $this->data,
            'active' => $this->active
        ];
    }
}

$session = new Session('abc123', ['user' => 'john'], true);
$serialized = $session->__serialize();
A2
B0
C1
D3
Attempts:
2 left
💡 Hint
Count the number of keys returned in the array from __serialize.

Practice

(1/5)
1. What is the main purpose of the __serialize method in a PHP class?
easy
A. To specify which object properties should be saved during serialization
B. To automatically convert an object to a string
C. To rebuild an object from saved data
D. To delete object properties before saving

Solution

  1. Step 1: Understand serialization

    Serialization means saving an object's data so it can be stored or sent.
  2. Step 2: Role of __serialize

    The __serialize method tells PHP which properties to save when serializing.
  3. Final Answer:

    To specify which object properties should be saved during serialization -> Option A
  4. Quick Check:

    __serialize controls saved data = A [OK]
Hint: Remember: __serialize picks what to save [OK]
Common Mistakes:
  • Confusing __serialize with __unserialize
  • Thinking __serialize rebuilds objects
  • Assuming it converts objects to strings automatically
2. Which of the following is the correct syntax for defining the __unserialize method in a PHP class?
easy
A. public function __unserialize($data)
B. function __unserialize(): array
C. private function __unserialize(array $data): string
D. public function __unserialize(array $data): void

Solution

  1. Step 1: Check method signature

    The __unserialize method must accept an array parameter and return nothing (void).
  2. Step 2: Match correct syntax

    public function __unserialize(array $data): void matches the correct signature: public function __unserialize(array $data): void.
  3. Final Answer:

    public function __unserialize(array $data): void -> Option D
  4. Quick Check:

    __unserialize signature = B [OK]
Hint: Look for array parameter and void return [OK]
Common Mistakes:
  • Missing type hint for parameter
  • Wrong return type specified
  • Using private instead of public visibility
3. What will be the output of the following PHP 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];
    }

    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();
medium
A. Name: Alice, Age: 30
B. Name: Alice, Age: 0
C. Name: , Age: 0
D. Error: Undefined index 'name'

Solution

  1. Step 1: Analyze __serialize output

    The __serialize method returns only the 'name' property, so 'age' is not saved.
  2. Step 2: Analyze __unserialize behavior

    When unserializing, 'name' is restored from data, but 'age' is set to 0 explicitly.
  3. Final Answer:

    Name: Alice, Age: 0 -> Option B
  4. Quick Check:

    Only 'name' saved, 'age' reset = C [OK]
Hint: Check what __serialize returns and how __unserialize sets properties [OK]
Common Mistakes:
  • Assuming all properties are saved automatically
  • Expecting original age to be restored
  • Ignoring explicit age reset in __unserialize
4. Identify the error in this PHP class using __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'];
    }
}
medium
A. Properties should be public for serialization
B. Missing return type in __serialize method
C. Using 'cost' key in __unserialize instead of 'price'
D. No constructor defined

Solution

  1. Step 1: Compare keys in __serialize and __unserialize

    The __serialize method saves 'price' key, but __unserialize tries to read 'cost' key.
  2. Step 2: Identify mismatch impact

    This mismatch causes an undefined index error when unserializing.
  3. Final Answer:

    Using 'cost' key in __unserialize instead of 'price' -> Option C
  4. Quick Check:

    Key mismatch in serialize/unserialize = A [OK]
Hint: Match keys exactly between __serialize and __unserialize [OK]
Common Mistakes:
  • Using different keys for same property
  • Ignoring array keys case sensitivity
  • Assuming missing keys won't cause errors
5. You want to securely save only non-sensitive user data from an object and restore it later. Which approach using __serialize and __unserialize is best?
hard
A. In __serialize, return only non-sensitive properties; in __unserialize, restore those and set sensitive ones to defaults
B. Serialize all properties automatically and trust the storage security
C. Use __serialize to encrypt all data and __unserialize to decrypt
D. Do not implement __serialize or __unserialize and rely on default serialization

Solution

  1. Step 1: Understand security needs

    Only non-sensitive data should be saved to avoid leaks.
  2. Step 2: Use __serialize and __unserialize properly

    Return only safe properties in __serialize and restore them in __unserialize, setting sensitive data to safe defaults.
  3. Final Answer:

    In __serialize, return only non-sensitive properties; in __unserialize, restore those and set sensitive ones to defaults -> Option A
  4. Quick Check:

    Selective save and safe restore = D [OK]
Hint: Save only safe data, reset sensitive on restore [OK]
Common Mistakes:
  • Saving all data without filtering
  • Assuming encryption happens automatically
  • Ignoring sensitive data in unserialize
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard