Serialization of Closure Not Allowed
Fatal error: Uncaught Exception: Serialization of 'Closure' is not allowedQuick Answer
You cannot serialize PHP closures with serialize() or store them in sessions. Extract the closure's logic into a named function or class, or use a library like opis/closure.
Why This Happens
PHP's built-in serialization does not support closures (anonymous functions). This error occurs when you try to serialize an object that contains a closure, store it in a session, or cache it. Closures capture scope and cannot be reliably converted to a string representation.
The Problem
$callback = function ($x) { return $x * 2; };
$_SESSION['callback'] = $callback; // Cannot serialize closureThe Fix
// Option 1: Use a named function or class
class Doubler {
public function __invoke(int $x): int {
return $x * 2;
}
}
$_SESSION['callback_class'] = Doubler::class;
// Option 2: Store the operation name
$_SESSION['operation'] = 'double';
$operations = [
'double' => fn($x) => $x * 2,
];Step-by-Step Fix
- 1
Find the closure
Identify which variable contains a closure that is being serialized. Check objects stored in sessions or caches.
- 2
Extract to a class
Convert the closure to an invokable class that implements the same logic and can be serialized.
- 3
Store references instead
Instead of serializing the closure, store an identifier or class name and recreate the callable when needed.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free