比方说,我有一个这样的课程:
<?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()
语句,但如果我想要的话可能会更容易。
如何在被调用的方法中访问调用者的参数?这甚至可能吗?
答案 0 :(得分:1)
我不确定这对您的情况是否有帮助,但您可以创建ReflectionFunction并使用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'));