Silex PHP微框架基于自动类型提示进行回调注入.例如,在Silex中,可以提供具有任意参数的Closure参数,如下所示:
$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) {
//...
});
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?我对将参数类型作为字符串不感兴趣.我正在寻找一种"无字符串"的全自动解决方案.换一种说法,
对于许多可能的论点:
$possible_arguments = [
new Class_A(),
new Class_B(),
new Class_C(),
new Another_Class,
$some_class
];
Run Code Online (Sandbox Code Playgroud)对于具有任意数量的任意参数的闭包,它只能包括上面定义的那些:
$closure = function (Class_B $b, Another_Class, $a) {
// Do something with $a and $b
};
Run Code Online (Sandbox Code Playgroud)我需要只获取匹配的参数,以便用它们调用闭包:
// $arguments is now [$possible_arguments[1], $possible_arguments[3]]
call_user_func_array($closure, $arguments);
Run Code Online (Sandbox Code Playgroud)我的猜测是使用反射.
http://php.net/manual/en/class.reflectionparameter.php
超级简单的例子:
function pre($var)
{
echo '<pre>' . var_export($var, true) . '</pre>';
}
interface TestInterface
{
}
class TestClass
{
public function __construct(TestInterface $testArg)
{
}
}
function TestFunc(TestInterface $testArg)
{
}
// for a class...
$className = 'TestClass';
$methodName = '__construct';
$argNumber = 0;
$ref = new ReflectionParameter([$className, $methodName], $argNumber);
pre($ref);
pre($ref->getClass());
// for a function...
$funcName = 'TestFunc';
$argNumber = 0;
$ref = new ReflectionParameter($funcName, $argNumber);
pre($ref);
pre($ref->getClass());
Run Code Online (Sandbox Code Playgroud)
我在stackoverflow上发现的另一个问题可能是你的问题的更好的答案:PHP反射 - 获取方法参数类型为字符串