Dump Source Code of Closure in PHP
Mai 22nd, 2013
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!
August 1st, 2014 at 15:05
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
August 1st, 2014 at 20:29
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!
Dezember 17th, 2014 at 12:46
thank you
Januar 12th, 2015 at 20:14
Simple and useful. Thank you.
Februar 15th, 2016 at 22:17
How could I evaluate the resulted code after modification, without using eval() ?