Menu
Coddy logo textTech

__serialize & __unserialize

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 49 of 91.

When you need to convert an object to a string for storage or transmission, PHP uses serialization. The __serialize() and __unserialize() magic methods give you control over exactly what data gets saved and how it's restored.

The __serialize() method returns an array of data to be serialized, while __unserialize() receives that array and rebuilds the object:

<?php
class Session {
    public function __construct(
        private string $userId,
        private array $data,
        private int $createdAt
    ) {}
    
    public function __serialize(): array {
        return [
            'userId' => $this->userId,
            'data' => $this->data
        ];
    }
    
    public function __unserialize(array $data): void {
        $this->userId = $data['userId'];
        $this->data = $data['data'];
        $this->createdAt = time();
    }
    
    public function getCreatedAt(): int {
        return $this->createdAt;
    }
}

$session = new Session("user123", ["theme" => "dark"], time());
$serialized = serialize($session);

$restored = unserialize($serialized);
echo "User: " . $restored->getCreatedAt();

Notice how createdAt is excluded from serialization and gets a fresh timestamp when unserialized. This is useful for excluding sensitive data, temporary values, or resources that can't be serialized like database connections.

These methods replaced the older __sleep() and __wakeup() methods in PHP 7.4, offering a cleaner approach where you work directly with data arrays instead of property names.

challenge icon

Challenge

Easy

Let's build a user profile caching system that demonstrates how __serialize() and __unserialize() give you control over what data gets saved and how it's restored.

You'll organize your code across two files:

  • UserProfile.php — Create a UserProfile class that represents a user's profile with caching capabilities. Use constructor promotion to define private properties for $userId (string), $username (string), $email (string), and $accessToken (string). Add a private $cachedAt property that stores when the profile was cached (set it to "not cached" initially in the constructor). Your class needs:
    • __serialize() — Returns an array containing only the userId, username, and email. The accessToken is sensitive and should never be serialized. The cachedAt timestamp will be regenerated on restore.
    • __unserialize() — Restores the userId, username, and email from the data array. Sets accessToken to "expired" (since tokens shouldn't persist).
    • getInfo() — Returns a string in the format: "[username] ([email]) - Token: [accessToken] - Cached: [cachedAt]"
  • main.php — Include the UserProfile file. You'll receive four inputs: a user ID, a username, an email, and an access token. Create a UserProfile instance with these values. Print three lines:
    • The original profile's info (before serialization)
    • Serialize the profile using serialize(), then unserialize it using unserialize() to create a restored profile. Print the restored profile's info.
    • Print "Token preserved: yes" or "Token preserved: no" depending on whether the restored profile's token matches the original (hint: it shouldn't match since tokens expire on restore)

This pattern is essential for caching user data safely — you want to store the profile information but never persist sensitive credentials like access tokens. When the profile is restored from cache, the token is marked as expired, forcing the application to obtain a fresh one.

Cheat sheet

The __serialize() and __unserialize() magic methods control what data gets saved during serialization and how objects are restored.

__serialize() returns an array of data to be serialized:

<?php
public function __serialize(): array {
    return [
        'userId' => $this->userId,
        'data' => $this->data
    ];
}

__unserialize() receives the array and rebuilds the object:

<?php
public function __unserialize(array $data): void {
    $this->userId = $data['userId'];
    $this->data = $data['data'];
    $this->createdAt = time();
}

Use serialize() to convert an object to a string and unserialize() to restore it:

<?php
$serialized = serialize($session);
$restored = unserialize($serialized);

These methods are useful for excluding sensitive data, temporary values, or resources that can't be serialized (like database connections). Properties can be regenerated with fresh values during unserialization.

Try it yourself

<?php

require_once 'UserProfile.php';

// Read inputs
$userId = trim(fgets(STDIN));
$username = trim(fgets(STDIN));
$email = trim(fgets(STDIN));
$accessToken = trim(fgets(STDIN));

// TODO: Create a UserProfile instance with the input values

// TODO: Print the original profile's info (before serialization)

// TODO: Serialize the profile, then unserialize it to create a restored profile

// TODO: Print the restored profile's info

// TODO: Print "Token preserved: yes" or "Token preserved: no"
// depending on whether the restored profile's token matches the original

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming