DesignPatternsPHP/DesignPatternsPHP · error · Exception

Cannot unserialize singleton

Error message

Cannot unserialize singleton

What it means

Singleton throws in __wakeup() to prevent unserialize() from creating a second instance, which would break the singleton guarantee. PHP's unserialization bypasses the constructor, so without this guard a clone would silently appear.

Source

Thrown at Creational/Singleton/Singleton.php:45

     * to use the singleton, you have to obtain the instance from Singleton::getInstance() instead
     */
    private function __construct()
    {
    }

    /**
     * prevent the instance from being cloned (which would create a second instance of it)
     */
    private function __clone()
    {
    }

    /**
     * prevent from being unserialized (which would create a second instance of it)
     */
    public function __wakeup()
    {
        throw new Exception("Cannot unserialize singleton");
    }
}

View on GitHub (pinned to 54254e0f2a)

Solutions

  1. Do not include the Singleton in serialized data; serialize only plain data/IDs and re-fetch the instance via Singleton::get()
  2. Use __serialize()/__sleep() on wrapper objects to drop the Singleton reference
  3. If you truly need unserialize, ensure the payload never contains the Singleton class

Example fix

// before
$data = unserialize($payload); // payload contains Singleton -> throws
// after
// store id only
$payload = serialize(['id' => 123]);
$data = unserialize($payload);
$singleton = Singleton::get();
Defensive patterns

Strategy: try-catch

Type guard

function containsSingleton(string $payload): bool {
    return str_contains($payload, 'Singleton');
}

Try / catch

try {
    $data = unserialize($payload);
} catch (Exception $e) {
    $data = null; // payload contained a Singleton; rebuild via Singleton::get()
}

Prevention

When it happens

Trigger: Calling unserialize() on a serialized payload containing a Singleton object, e.g. data stored in sessions, caches, or cookies that captured a Singleton reference.

Common situations: Storing objects containing Singleton references in PHP sessions or serialize()-based caches and later unserializing them; legacy code that serialized whole object graphs.

Related errors


AI-assisted analysis of DesignPatternsPHP/DesignPatternsPHP@54254e0f2a (2026-09-01). Data as JSON: /api/errors/bf8c48ab730efab2. Report an issue: GitHub.