<?php
class TestClass {
}
$abc = "testABC";
$xyz = new TestClass();
$test = true;
$x = function () use ($test, $xyz, $abc) {
echo $abc;
var_dump($test, $xyz);
var_dump($this);
};
$x->bindTo(new TestClass, "TestClass");
$x();
echo packAnonFunction($x, $test, $xyz, $abc);
function packAnonFunction($payload, ...$args) {
$func = new ReflectionFunction($payload);
$filename = $func->getFileName();
$start_line = $func->getStartLine() - 1;
$end_line = $func->getEndLine();
$length = $end_line - $start_line;
var_dump($func->getClosureThis());
$source = file($filename);
$body = implode("", array_slice($source, $start_line, $length));
$body = preg_replace('/(?:(?:(\$[a-z]+)\s\=)|return)\sfunction/', '\\$payload = function', $body);
if(preg_match('/use\s\((\$[a-zA-Z0-9]+(?:,\s\$[a-zA-Z0-9]+)*)\)/', $body, $matches)) {
$vars = $matches[1];
if(strpos($vars, ', ') !== false) {
$parts = explode(', ', $vars);
} else {
$parts = [$vars];
}
$body = str_replace(" use (" . $vars . ")", "", $body);
} else {
$parts = [];
}
if(strpos($body, '$this') !== false) {
$parts[] = '$this';
$args[count($parts) - 1] = $func->getClosureThis();
}
$return = [];
foreach($parts as $key => $variable) {
$return[$variable] = $args[$key];
}
$variableString = "";
foreach($return as $var => $value) {
$value = serialize($value);
$variableString .= "\t{$var} = unserialize('{$value}');\n";
}
$body = str_replace("{\n", "{\n" . $variableString, $body);
return $body;
}
preferences:
44.46 ms | 402 KiB | 5 Q