dinamik fonksiyon argümanları

0 Cevap

I'm passing all my calls to a main mapping function and then it should dynamically call other function based on a string (until this part, things are easy) the problem is that I want to pass arguments to the second function and these parameters may vary. The following is given (should not be changed):

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

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

ve şimdi haritalama fonksiyonu geliyor

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

Ve sonra bu eşleme çalışacaktır:

$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 when the function has more than one argument (which can easily happen). I'm expecting to have the switch case and based on how the case parameters are filled, the line $this->{$fn_name}($var); should work.

Eğer tavsiye ya da bana fikir verin, fonksiyonları (test1, dnm2) yapısı değiştirilemez bilerek lütfen. Ben aniden func_get_args() kullanmaya başlamak veya func_get_arg() DEĞİL olabilir

0 Cevap