Type of hint when calling arbitrary functions (closures) in PHP

Possible duplicate:
PHP Reflection - Get Method Type of Parameter as String

The Silex PHP microframe performs a backlash based on an automatic type hint. For example, in Silex, you can provide a Closure argument with arbitrary arguments, for example:

$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) { //... }); 

How can I do it? I am not interested in getting parameter types as strings. I am looking for a fully automatic "no line" solution. In other words,

  • For a number of possible arguments:

     $possible_arguments = [ new Class_A(), new Class_B(), new Class_C(), new Another_Class, $some_class ]; 
  • To close with any number of arbitrary arguments, which can include only those defined above, only once:

     $closure = function (Class_B $b, Another_Class, $a) { // Do something with $a and $b }; 
  • I need to get only matching arguments to cause a closure with them:

     // $arguments is now [$possible_arguments[1], $possible_arguments[3]] call_user_func_array($closure, $arguments); 
+4
source share
2 answers

Indeed, they use Reflection , especially in the ControllerResolver class .

If you let me simplify the inclusion of only one Closure case and only object type arguments:

 $availableArguments = array($a, new B(), $c); $arguments = array(); $reflection = new \ReflectionFunction($callback); // $callback is a Closure foreach ($reflection->getParameters() as $param) { if ($paramClass = $param->getClass()) { foreach ($availableArguments as $proposedArgument) { if ($paramClass->isInstance($proposedArgument)) { $arguments[] = $proposedArgument; break; } } } } call_user_func_array($callback, $arguments); 
+3
source

My guess will be using reflection.

http://php.net/manual/en/class.reflectionparameter.php

Super simple example:

 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()); 

Another question I found on stackoverflow might be the best answer to your question: PHP Reflection - Get Method Parameter Type As String

+5
source

All Articles