Skip to content

Instantly share code, notes, and snippets.

@munro
Created January 13, 2012 20:56
Show Gist options
  • Save munro/1608654 to your computer and use it in GitHub Desktop.
Save munro/1608654 to your computer and use it in GitHub Desktop.
PHP Macros
<?php
// TODO: bind macroed function to original function's scope
function getFunctionCode($rfn) {
return implode(array_slice(
preg_split('/\r?\n/', file_get_contents($rfn->getFileName())),
$rfn->getStartLine() - 1,
$rfn->getEndLine() - $rfn->getStartLine() + 1
));
}
function createClass($class, $args) {
$ref_class = new ReflectionClass($class);
return $ref_class->newInstanceArgs($args);
}
function evalValue($code) {
eval('$val = ' . $code . ';');
return $val;
}
function macro($fn, $rewrite) {
return evalValue(
$rewrite(
preg_replace(
'/^.*function[^(]+/',
'$myfn = function',
getFunctionCode(
createClass(
'ReflectionFunction',
array($fn))))));
}
// Testing
$a = 'outer';
$myfunction = function () {
echo "Outer Hello!\n";
$a = 'inner';
return function () use ($a) {
echo "Inner Hello:" . $a . "\n";
};
};
$before = $myfunction();
$before();
$wee = macro($before, function ($fn) {
return str_replace('Hello', 'Hello World', $fn);
});
echo "Macroed!\n";
$wee();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment