Dynamic function arguments

I pass all my calls to the main matching function and then it must dynamically call another function based on the line (until this part becomes easy) the problem is that I want to pass the arguments to the second function, and these parameters may differ. The following is given (should not be changed):

function test1($x){
     echo $x;
}

function test2($x, $y){
     echo $x * $y;
}

and now the display function appears

function mapping ($str){
      switch ($str){
          case 'name1':
              $fn_name = 'test1';
              $var = 5;
              break;
          case 'name2':
              $fn_name = 'test2';
              $var = 5;
              break;
      }
      $this->{$fn_name}($var);
}

And then this will start the display:

$this->mapping('name1');
$this->mapping('name2');   // This one will crash as it need two variables

Of course, the above is simplified to focus on the problem, not the purpose of the code. The problem is that the function has more than one argument (which can easily happen). I expect that I will have a switch case and based on how the case parameters are populated, the line should work. $this->{$fn_name}($var);

, , (test1, test2) . func_get_args() func_get_arg()

+5
2

ReflectionFunction invokeArgs() :

function mapping ($str) {
    switch ($str) {
        case 'name1':
            $fn_name = 'test1';
            $fn_args = array(5);
            break;
        case 'name2':
            $fn_name = 'test2';
            $fn_args = array(5, 10);
            break;
    }

    $function = new ReflectionFunction($fn_name);
    $function->invokeArgs($fn_args);
}
+5

mapping() , :

public function __call($method, $args)
{
    // possibly validate $method first, e.g. with a static map
    return call_user_func_array($method, $args);
}

:

function foo($foo) { echo $foo; }
function bar($foo, $bar) { echo "$foo - $bar"; }

$this->foo('foo'); // outputs 'foo'
$this->bar('foo', 'bar'); // outputs 'foo - bar'

, foo() bar() __call().

, . , , ?:)

+2

All Articles