比方说,我有一个这样的班级:
<?php
class ExampleClass {
public function callerOne($arg1, $arg2) {
return $this->calledMethod(function($arg1, $arg2) {
// do something
});
}
public function callerTwo($arg1) {
return $this->calledMethod(function($arg1) {
// do something
});
}
protected function calledMethod(Closure $closure)
{
// How to access caller's arguments, like func_get_args()
$args = get_caller_method_args();
return call_user_func_array($closure, $args);
}
}在上面的示例中,方法calledMethod将传递的闭包包装成某种东西,例如在beginTransaction()和endTransaction()之间扭曲它,但是我需要访问调用者方法参数。
我知道,在将闭包传递给use时,可能的解决方案是使用calledMethod()语句,但如果我想要的是可能的话,就会容易得多。
如何访问调用方的参数,在被调用的方法中?这可能吗?
发布于 2015-04-19 08:19:08
我不确定这在您的情况下是否有帮助,但是您可以创建ReflectionFunction并使用反射功能::invokeArgs,后者调用函数并将其参数作为数组传递。
<?php
$closure = function () {
echo 'Hello to: ' . implode(', ', func_get_args()) . PHP_EOL;
};
$reflection = new ReflectionFunction($closure);
// This will output: "Hello to: foo, bar, baz"
$reflection->invokeArgs(array('foo', 'bar', 'baz'));https://stackoverflow.com/questions/29727201
复制相似问题