得到這個工作,我寫了下面的功能,翻出功能代碼,匹配任何use(...)
條款和重命名變量它叫做。最後,它會將use(...)
變量指定爲無法序列化的字符串。
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;
$source = file($filename);
$body = implode("", array_slice($source, $start_line, $length));
$body = preg_replace('/(\$[a-z]+)\ \=\ function/', '\\$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];
}
$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(" use (" . $vars . ")", "", $body);
$body = str_replace("{\n", "{\n" . $variableString, $body);
}
return $body;
}
你可以只使用這樣的:
$abc = "testABC";
$xyz = new TestClass();
$test = true;
$x = function() use ($test, $xyz, $abc) {
echo $abc;
var_dump($test, $xyz);
};
echo packAnonFunction($x, $test, $xyz, $abc);
唯一的滯後我是不是要解決的是,你得把ARGS($test, $xyz, $abc
)以相同的順序因爲您分配了use(...)
聲明。
看看它的實際操作:https://3v4l.org/89pXm
所以,你對此有何看法?