Luminova Framework

PHP Luminova: Anonymous Class and Closure Serializer

Last updated: 2026-11-28 20:57:12

Serialize closures and anonymous objects for later restoration.

Luminova’s Anonymous Object Serializer stores closures and anonymous class instances as strings. A restored closure can retain captured values and, when available, its original binding. Payloads are signed by default with the application key or a supplied key. Restore payloads from trusted application storage because restoration reconstructs executable PHP.


Limitations

  • Restored code is evaluated without the original namespace and use imports. Use fully qualified class names (\stdClass) inside serialized closures and anonymous classes.
  • Captured variables must be scalars, arrays, null, objects that can be serialized, or the closure itself (for recursion). Other values, such as resources, throw a RuntimeException.
  • A captured closure is restored as a reference to the closure itself, which is what makes recursion work. Capturing a different closure is not supported.
  • $this is rebound only when the original object is still available in the same PHP process. In a new request or process, the closure keeps its class scope but is not bound to an object. Static closures are never bound.
  • Anonymous classes are rebuilt from their source, so runtime state is not preserved. Literal constructor arguments stay in the code. A variable passed to new class($name) is captured from the class property at the same position, so keep the property order the same as the argument order.
  • The magic constants __FILE__, __LINE__, __DIR__, __CLASS__, __METHOD__ and __NAMESPACE__ are replaced with resolver calls that return the original context when the restored code runs. __FUNCTION__ and __TRAIT__ are left unchanged.
  • In non-production environments, the source file and line are stored in the payload to improve error messages. During restoration, the working directory is temporarily changed to the source file's directory when that file still exists.

Examples

Serialize a Simple Closure

Convert any anonymous function into a string that can be stored in a database, cache, or file.

use Luminova\Utility\Serializer;

$fn = function(string $name): string {
    return "Hello, {$name}!";
};

$serialized = Serializer::serialize($fn);

echo $serialized;
// Returns a string representation of the closure.

Unserialize and Execute

Serialize a closure from a class method, verify the signed payload, then restore and call it. Configure app.key before running the example.

Example

use Luminova\Utility\Serializer;

final class Greetings
{
    public static function save(): string
    {
        $greet = static function (string $name): string {
            return "Hello, {$name}!";
        };

        return Serializer::serialize($greet);
    }
}

$payload = Greetings::save();

if (Serializer::isValid($payload)) {
    $closure = Serializer::unserialize($payload);

    if ($closure instanceof Closure) {
        echo $closure('World');
    }
}

Key point:The restored closure behaves like the original.Parameters and return types are preserved.

Unserializing the same payload more than once in a process returns the same cached closure instance.


Serialize an Anonymous Class

Anonymous classes are serialized and restored the same way as closures.

use Luminova\Utility\Serializer;

$object = new class('World') {
    public function __construct(private string $name) {}

    public function greet(): string {
        return "Hello, {$this->name}!";
    }
};

$serialized = Serializer::serialize($object);
$restored = Serializer::unserialize($serialized);

echo $restored->greet();
// Hello, World!

Note:The object is rebuilt from source, so its state at the time of serialization is not preserved.Passing an object that is neither a closure nor an anonymous class to serialize throws a RuntimeException.


Signing with a Custom Key

Payloads are signed by default using env('app.key'). Pass your own key to sign and verify with a different one.

use Luminova\Utility\Serializer;

$key = 'my-secret-key';

$serialized = Serializer::serialize(
    fn(int $x): int => $x * 2, 
    key: $key
);

$closure = Serializer::unserialize($serialized, [
    'key' => $key
]);

echo $closure(4);
// 8

Note:If the payload is signed and the key does not match, unserialize throws a RuntimeException.

To skip signing, set $sign to false.

$serialized = Serializer::serialize($fn, sign: false);

Closures Updating Variables by Reference

When a closure captures a variable by reference (&$var), changes made inside the closure are kept between calls of the restored closure. The original variable is not affected, because the restored closure holds its own copy.

use Luminova\Utility\Serializer;

$counter = 0;
$obj = new \stdClass();
$obj->value = 10;

// Capture $counter by reference and $obj by value
$fn = function () use (&$counter, $obj) {
    $counter++;
    $obj->value++;
    return [$counter, $obj->value];
};

$packed = Serializer::serialize($fn);

$restored = Serializer::unserialize($packed);

var_export($restored());
// [1, 11]

var_export($restored());
// [2, 12]

var_export($restored());
// [3, 13]

Serialize and Restore Recursive Closure

A closure that calls itself through use (&$fn) keeps its recursion after it is restored.

use Luminova\Utility\Serializer;

$fn = function (int $n) use (&$fn) {
    return $n <= 1 ? 1 : $n * $fn($n - 1);
};

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored(5);
// 120

Closures with use Variables

Closures often depend on external variables. These values are captured and restored.

use Luminova\Utility\Serializer;

$testUse = 'TestVar';

$fn = function(string $ctx) use ($testUse): string {
    return "Hello {$ctx}, {$testUse}";
};

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored('Closure');
// Hello Closure, TestVar

Note:

The value of $testUse is stored in the payload,so the restored closure still has access to it.


Capturing Objects

Objects captured with use are serialized with the closure and restored with it.

use Luminova\Utility\Serializer;

$obj = new \stdClass();
$obj->name = 'ObjectName';

$fn = function() use ($obj) {
    return "Name: {$obj->name}";
};

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored();
// Name: ObjectName

Note:The object state at the time of serialization is preserved.The object must be serializable and its class must be available when restoring.


Binding to $this Scope

Closures created inside objects keep their class scope. They are also bound to the original object when that object is still available in the same process.

use Luminova\Utility\Serializer;
use Closure;

$obj = new class {
    public string $prefix = 'Scope';

    public function getClosure(): Closure {
        return function(string $ctx) {
            return "{$this->prefix}: {$ctx}";
        };
    }
};

$fn = $obj->getClosure();

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored('Hello');
// Scope: Hello

Important:

$this is rebound only within the same process that serialized the closure.If you restore it in another request or process, the closure is not bound to an object,so avoid $this in closures that you plan to store and restore later.Static closures are never bound to an object.


Nested Closures

Closures defined inside other closures are handled correctly.

use Luminova\Utility\Serializer;

$fn = function(string $ctx) {
    $inner = function(string $name) use ($ctx) {
        return "{$ctx} -> {$name}";
    };

    return $inner('Nested');
};

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored('Outer');
// Outer -> Nested

Multiple Captured Variables

Closures can capture multiple scalar and array variables.

use Luminova\Utility\Serializer;

$a = 1;
$b = 2;
$c = [3, 4];

$fn = function() use ($a, $b, $c) {
    return $a + $b + array_sum($c);
};

$packed = Serializer::serialize($fn);
$restored = Serializer::unserialize($packed);

echo $restored();
// 10

Inspect and Validate a Payload

Check what a stored string contains before you restore it.

use Luminova\Utility\Serializer;

$serialized = Serializer::serialize(fn() => 'ok');

Serializer::isAnonymous($serialized); // true
Serializer::isClosure($serialized);   // true
Serializer::isValid($serialized);     // true

Note:isAnonymous and isClosure only check the payload format.They do not verify the signature or restore the object.

isValid returns false when the signature does not match, instead of throwing.


Class Definition

  • Full namespace: Luminova\Utility\Serializer
  • This class is final.
  • The constructor is private, use the static methods to create and restore payloads.

Constants

ConstantTypeValueDescription
VERSIONstring1.0.0The serializer payload version, stored in the payload header.

Methods

serialize

Serialize an anonymous class or closure to string.

This method converts a closure, arrow function, or anonymous class into a string representation that captures its source code, scope, and any variables it uses. Closures that capture variables from their surrounding scope are supported.

The payload is signed by default. Signing requires a key, either from $key or from env('app.key').

public static function serialize(
    object $anonymous,
    bool $sign = true,
    ?string $key = null
): string

Parameters:

ParameterTypeDescription
$anonymousobjectThe anonymous class instance or closure to serialize.
$signboolWhether to sign the serialized payload for integrity verification (default: true).
$keystring\|nullOptional signing key (default: null).

Return:

string - Returns the serialized string representation of the closure or anonymous class.

Throws:

  • Luminova\Exceptions\RuntimeException - If the object is not a closure or anonymous class, the source code cannot be extracted, a captured variable is not supported, or signing is enabled and no key is available. Any other error raised while serializing is rethrown as a RuntimeException.

unserialize

Unserialize an anonymous class or closure from string.

This method takes a string produced by serialize and rebuilds the original object. It verifies the signature when the payload is signed, evaluates the code in the original class scope, and binds $this when the original object is still available in the current process.

Restored closures are cached per payload, so unserializing the same string again returns the same closure. Anonymous classes are created on each call.

public static function unserialize(string $serialized, array $options = []): ?object

Parameters:

ParameterTypeDescription
$serializedstringSerialized payload generated by {@see self::serialize()}.
$optionsarray<string,mixed>Optional restoration options: (default: []).

Return:

object|null - Returns the restored closure or anonymous class instance, or null if the string is not a serialized anonymous object produced by this class.

Throws:

  • Luminova\Exceptions\RuntimeException - If signature verification fails, the payload is signed and no key is available, or the object cannot be rebuilt due to invalid code or evaluation errors.

isValid

Verify whether a serialized payload is valid.

This method checks that the string is a payload produced by this class, restores the payload container safely, and verifies the signature when one is present. A payload without a signature is considered valid. An invalid signature returns false.

public static function isValid(string $serialized, array $options = []): bool

Parameters:

ParameterTypeDescription
$serializedstringSerialized closure payload to validate.
$optionsarray<string,mixed>Validation options: (default: []).

Return:

bool - Returns true if the payload is valid, otherwise false.

Throws:


isClosure

Check if a serialized string is a closure.

This method performs a lightweight format check. It returns true when the string was produced by this class and contains a closure or arrow function payload. It does not restore the object or verify the signature.

public static function isClosure(string $serialized): bool

Parameters:

ParameterTypeDescription
$serializedstringThe serialized data to inspect.

Return:

bool - Returns true if the string is a serialized closure, false otherwise, including for anonymous class payloads.


isAnonymous

Check if a serialized string is an anonymous function or an anonymous class.

This method performs a lightweight format check. It returns true when the string was produced by this class and contains either a closure, arrow function, or anonymous class payload. It does not restore the object or verify the signature.

public static function isAnonymous(string $serialized): bool

Parameters:

ParameterTypeDescription
$serializedstringThe serialized data to inspect.

Return:

bool - Returns true if the string contains a closure or anonymous class payload, false otherwise.