Skip to content

Instantly share code, notes, and snippets.

@lastguest
Last active February 9, 2017 10:48
Show Gist options
  • Save lastguest/215993bc7876c7a8bb127e8c5940919e to your computer and use it in GitHub Desktop.
Save lastguest/215993bc7876c7a8bb127e8c5940919e to your computer and use it in GitHub Desktop.
[Closure Source] Get Closure source code. #tags: PHP, reflection, source
<?php
function closure_source(Closure $c) {
$rfx = new ReflectionFunction($c); $args = [];
foreach($rfx->getParameters() as $p)
$args[] = ($p->isArray() ? 'array ' : ($p->getClass() ? $p->getClass()->name . ' ' : ''))
. ($p->isPassedByReference() ? '&' : '') . '$' . $p->name
. ($p->isOptional() ? ' = ' . var_export($p->getDefaultValue(), true) : '');
return 'function(' . implode(',', $args) . "){\n"
. implode('',array_slice(file($rfx->getFileName()),
$s=$rfx->getStartLine(),$rfx->getEndLine()-$s-1)).'}';
}
@ahsankhatri
Copy link

Approach is good but it wont work with closure_source(function() {echo 'one liner test';});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment