我有一个已经定义的闭包,我想在执行它时在其中注入代码。
这是一个例子:
$predefined = "print 'my predefined injected code<br />';";
$closure = function () {
print 'hello<br />';
};
call_user_func_array($closure, array());
// output : hello
我想混合两种代码:预定义的代码和闭包的代码。
修改后,我希望我的闭包看起来像这样
$closure = function () {
print 'my predefined injected code<br />';
print 'hello<br />';
};
是否可以在执行之前在闭包中插入一些代码?
注意:我不能使用将代码作为字符串的“create_function”,因此可以轻松修改。闭包已经定义并且以某种方式定义(通过采用回调参数而不是字符串参数的函数)。
感谢您的帮助。
EDIT:
这是解决方案
function hackClosure($closure, $inject_code)
{
$reflection = new ReflectionFunction($closure);
$tmp = $reflection->getParameters();
$args = array();
foreach ($tmp as $a) array_push($args, '$'.$a->getName() . ($a->isDefaultValueAvailable() ? '=\''.$a->getDefaultValue().'\'' : ''));
$file = new SplFileObject($reflection->getFileName());
$file->seek($reflection->getStartLine()-1);
$code = '';
while ($file->key() < $reflection->getEndLine())
{
$code .= $file->current();
$file->next();
}
$start = strpos($code, '{')+1;
$end = strrpos($code, '}');
return create_function(implode(', ', $args), substr($code, $start, $end - $start) . $inject_code);
}
$theClosure = function () { print 'something'; };
$inject_code = "print ' to say';";
$func = hackClosure($theClosure, $inject_code);
$func();
它呈现
something to say
代替
something