Recently I was required to dump the source code of a closure in php, for debugging purposes. Here comes my first working approach. As it is just the first approach, I would really appreciate comments on what is not working for you, and what should be additionally possible. Here comes the code:

function closure_dump(Closure $c) {
    $str = 'function (';
    $r = new ReflectionFunction($c);
    $params = array();
    foreach($r->getParameters() as $p) {
        $s = '';
        if($p->isArray()) {
            $s .= 'array ';
        } else if($p->getClass()) {
            $s .= $p->getClass()->name . ' ';
        }
        if($p->isPassedByReference()){
            $s .= '&';
        }
        $s .= '$' . $p->name;
        if($p->isOptional()) {
            $s .= ' = ' . var_export($p->getDefaultValue(), TRUE);
        }
        $params []= $s;
    }
    $str .= implode(', ', $params);
    $str .= '){' . PHP_EOL;
    $lines = file($r->getFileName());
    for($l = $r->getStartLine(); $l < $r->getEndLine(); $l++) {
        $str .= $lines[$l];
    }
    return $str;
}

Imagine you have the following closure:

$f = function (Closure $a, &$b = -1, array $c = array())
  use ($foo) 
{
    echo $this->name;
    echo 'test';
};

Then closure_dump() will give you the following output:

function (Closure $a, &$b = -1, array $c = array (
)){
 use ($foo)
{
    echo $this->name;
    echo 'test';
};

As you can see, the debugging output is already nice, there are only problems with the formatting of the default value of the third, array, parameter. Maybe I’ll enhance this once. So far it should be at least useful for debugging.

Happy Coding! :)

5 Responses to “Dump Source Code of Closure in PHP”

  1. domger Says:

    it works good enough for me,
    thx for that!

    maybe you add some license info here to clarify that anyone is allowed to use/copy/share it.
    -domger

  2. thorsten Says:

    Glad to see that it helped you.

    The code posted here is public domain. You can use it like you wish. Thinking about do create a small composer package from that and post it on Github. This would be BSD-3 then, meaning you can do what you want with it unless you keep the copyright notice.

    Open source rules :)

    Have fun!

  3. خرید vpn Says:

    thank you

  4. Carlos Rosao Says:

    Simple and useful. Thank you.

  5. Abdelrahman Omran Says:

    How could I evaluate the resulted code after modification, without using eval() ?

Leave a Reply