PHPackages                             vchagin/superclosure - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. vchagin/superclosure

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

vchagin/superclosure
====================

Serialize Closures, including their context

265PHP

Since May 29Pushed 6y ago1 watchersCompare

[ Source](https://github.com/vchagin/superclosure)[ Packagist](https://packagist.org/packages/vchagin/superclosure)[ RSS](/packages/vchagin-superclosure/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

PHP Super Closure
=================

[](#php-super-closure)

[![Latest Stable Version](https://camo.githubusercontent.com/8c4e3e3f33d60314c0519425e68963d3d470e8d14240717838213641773c202f/68747470733a2f2f706f7365722e707567782e6f72672f6a6572656d65616d69612f7375706572636c6f737572652f762f737461626c652e706e67)](https://packagist.org/packages/jeremeamia/superclosure)[![Total Downloads](https://camo.githubusercontent.com/cd71fa6803dafa9507597022735a4c3a9636105a4201f73be0dba7e3ba054d84/68747470733a2f2f706f7365722e707567782e6f72672f6a6572656d65616d69612f7375706572636c6f737572652f646f776e6c6f6164732e706e67)](https://packagist.org/packages/jeremeamia/superclosure)[![Build Status](https://camo.githubusercontent.com/5e563726847746db9506c30efafa99ae588c0b14157adb9834f93be0a167dbb8/68747470733a2f2f7472617669732d63692e6f72672f6a6572656d65616d69612f73757065725f636c6f737572652e7376673f6272616e63683d6d756c7469706c652d70617273657273)](http://travis-ci.org/#!/jeremeamia/super_closure)[![GitTip](https://camo.githubusercontent.com/6448100c21b4f81fa98b30fb7d1a72e0a1e28bcdd4a374afb875c2175f061b09/687474703a2f2f696d672e736869656c64732e696f2f6769747469702f6a6572656d65616d69612e737667)](https://www.gittip.com/jeremeamia)

Have you ever seen this?

> Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'

It's true! If you try to serialize a `Closure`, PHP will throw an exception and tell you that it is not allowed. But even though it is not "allowed" by PHP, the Super Closure library ([jeremeamia/superclosure](http://packagist.org/packages/jeremeamia/SuperClosure) on Packagist) makes it **possible**.

I'm not joking, *you really can serialize a PHP closure*!

```
require 'vendor/autoload.php';

use SuperClosure\SerializableClosure;

$greeting = 'Hello';
$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$helloWorld();
//> Hello, World!
$helloWorld('Jeremy');
//> Hello, Jeremy!

$serialized = serialize($helloWorld);
$unserialized = unserialize($serialized);

$unserialized();
//> Hello, World!
$unserialized('Jeremy');
//> Hello, Jeremy!
```

Yep, pretty cool huh?

Tell Me More!
-------------

[](#tell-me-more)

It all started way back in the beginning of 2010 when PHP 5.3 was starting to gain traction. I wrote a blog post called [Extending PHP 5.3 Closures with Serialization and Reflection](http://www.htmlist.com/development/extending-php-5-3-closures-with-serialization-and-reflection/) on my former employers' blog, [HTMList](http://www.htmlist.com), showing how it can be done. Since then I've made a few iterations on the code, and this most recent iteration brings with it a generally more robust solution that takes advantage of the fabulous [nikic/php-parser](https://github.com/nikic/PHP-Parser) library.

### Features

[](#features)

- Grants the ability to serialize closures
- Handles closures with used/inherited/imported variables
- Handles closures that use other closures
- Handles closures that reference class names in the parameters or body
- Handles recursive closures (PHP 5.4+ only)
- Allows you to get the code of a closure
- Allows you to get the names and values of variables used by a closure
- Allows you to get an Abstract Syntax Tree (AST) representing the code of a closure
- Replaces magic constants with their expected values so that the closure behaves as expected after unserialization
- Uses an accurate parsing method of a context-free grammar via the [nikic/php-parser](https://github.com/nikic/PHP-Parser) library
- PSR-0 compliant and installable via Composer

### Caveats

[](#caveats)

1. For any variables used by reference (e.g., `function () use (&$vars, &$like, &$these) {…}`), the references are not maintained after serialization/unserialization. The only exception is when (in PHP 5.4+ only) the used variable is a reference to the `SerializableClosure` object being serialized, which is the case with a recursive function. For some reason — *that I actually don't quite understand* — this works.
2. If you have two closures defined on a single line (you shouldn't do this anyway), you will not be able to serialize either one since it is ambiguous which closure's code should be parsed.
3. Because the technique to acquire the code and context of the closure requires reflection and full AST-style parsing, the performance of serializing a closure is likely not good.
4. **Warning**: Both `eval()` and `extract()` are required to unserialize the closure. These functions are considered dangerous by many, so you will have to evaluate whether or not you actual want to be using this library if these functions concern you. These functions *must* be used to make this technique work.

Installation
------------

[](#installation)

To install the Super Closure library in your project using Composer, first add the following to your `composer.json`config file.

```
{
    "require": {
        "jeremeamia/superclosure": "~1.0"
    }
}
```

Then run Composer's install or update commands to complete installation. Please visit the [Composer homepage](http://getcomposer.org) for more information about how to use Composer.

Why Would I Need To Serialize Closures?
---------------------------------------

[](#why-would-i-need-to-serialize-closures)

Well, since you are here looking at this README, you may already have a use case in mind. Even though this concept began as an experiment, there have been some use cases that have come up in the wild.

For example, in a [video about Laravel 4 and IronMQ](http://vimeo.com/64703617) by [UserScape](http://www.userscape.com), at about the 7:50 mark they show how you can push a closure onto a queue as a job so that it can be executed by a worker. This is nice because you do not have to create a whole class for a job that might be really simple. The closure serialization is done by a [class in the Laravel 4 framework](https://github.com/illuminate/support/blob/master/SerializableClosure.php) that is based on one of my older versions of SuperClosure.

Essentially this library let's you create closures in one process and use them in another. It would even be possible to provide closures (or algorithms) as a service through an API.

Who Is Using Super Closure?
---------------------------

[](#who-is-using-super-closure)

- [Laravel 4](https://github.com/laravel/framework) - Serializes a closure to potentially push onto a job queue.
- [HTTP Mock for PHP](https://github.com/InterNations/http-mock) - Serialize a closure to send to remote server within a test workflow.
- [Jumper](https://github.com/kakawait/Jumper) - Serialize a closure to run on remote host via SSH.
- [nicmart/Benchmark](https://github.com/nicmart/Benchmark) - Uses the `ClosureParser` to display a benchmarked Closure's code.
- Please let me know if and how your project uses Super Closure.

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/b32fe7b2f2f5e2d3e515668342c00c71d77933b1762b54a2997e04d42410af9d?d=identicon)[Vladimir Chagin](/maintainers/Vladimir%20Chagin)

---

Top Contributors

[![vchagin](https://avatars.githubusercontent.com/u/16269904?v=4)](https://github.com/vchagin "vchagin (3 commits)")

### Embed Badge

![Health badge](/badges/vchagin-superclosure/health.svg)

```
[![Health](https://phpackages.com/badges/vchagin-superclosure/health.svg)](https://phpackages.com/packages/vchagin-superclosure)
```

###  Alternatives

[monsoonconsulting/magento2-pwa

Adds a service worker to Magento2 to enable PWA features.

2322.9k](/packages/monsoonconsulting-magento2-pwa)[yii2mod/yii2-selectize

selectize.js wrapper for yii2

1730.7k1](/packages/yii2mod-yii2-selectize)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
