【发布时间】:2012-12-07 17:26:12
【问题描述】:
Silex PHP 微框架基于自动类型提示进行回调注入。例如,在 Silex 中,可以提供带有任意参数的闭包参数,如下所示:
$app->get('/blog/show/{postId}/{commentId}', function ($commentId, $postId) {
//...
});
$app->get('/blog/show/{id}', function (Application $app, Request $request, $id) {
//...
});
// following works just as well - order of arguments is not important
$app->get('/blog/show/{id}', function (Request $request, Application $app, $id) {
//...
});
我该怎么做?我对将参数类型作为字符串获取不感兴趣。我正在寻找一种“无条件”的全自动解决方案。换句话说,
-
对于一些可能的参数:
$possible_arguments = [ new Class_A(), new Class_B(), new Class_C(), new Another_Class, $some_class ]; -
对于具有任意数量的任意参数的闭包,它只能包含上面定义的那些参数:
$closure = function (Class_B $b, Another_Class, $a) { // Do something with $a and $b }; -
我只需要获取匹配的参数才能使用它们调用闭包:
// $arguments is now [$possible_arguments[1], $possible_arguments[3]] call_user_func_array($closure, $arguments);
【问题讨论】:
-
他们将使用Reflection。闭包在内部被转换为 Closure 类的实例,反射在其上工作就像任何其他对象一样。您应该能够通过检查对象的
__invoke()方法来获取闭包的参数列表。