代码之家  ›  专栏  ›  技术社区  ›  Incognito

动态函数、变量输入

  •  0
  • Incognito  · 技术社区  · 14 年前

    现在,假设我有这样的代码…

    $some_var=returnsUserInput();
    
    function funcA($a) {...}
    function funcB($a,$b) {...}
    function funcC($a,$b,$c) {...}
    
    $list[functionA] = "funcA";
    $list[functionB] = "funcB";
    $list[functionC] = "funcC";
    
    $temp_call = list[$some_var];
    
    //Not sure how to do this below, just an example to show the idea of what I want.
    $temp_call($varC1,varC2,$varC3);
    $temp_call($varB1,varB2);
    $temp_call($varA1);
    

    我的问题从这里开始,如何根据这些参数在参数中指定适当的变量?我有一些想法,比如为每个指定这些的函数创建一个列表,但是我真的希望看到一个优雅的解决方案。

    3 回复  |  直到 12 年前
        1
  •  1
  •   David Pratte    14 年前

    你需要使用 call_user_func 或者调用用户函数数组。

    <?php
    // if you know the parameters in advance.
    call_user_func($temp_call, $varC1, $varC2);
    // If you have an array of params.
    call_user_func_array($temp_call, array($varB1, $varB2));
    ?>
    
        2
  •  1
  •   Kieran Allen    14 年前

    你想要像下面这样的东西吗?

    function test()
    {
        $num_args   =   func_num_args();
    
        $args       =   func_get_args();
    
        switch ($num_args) {
            case 0:
                return 'none';
            break;
    
    
            case 1: 
                return $args[0];
    
            break;
    
            case 2:
                return $args[0] . ' - ' . $args[1];
            break;
    
            default:
    
                return implode($args, ' - ');
            break;
        }
    }
    
    echo test(); // 'none'
    echo test(1); // 1
    echo test(1, 2); // 1 - 2
    echo test(1, 2, 3); // 1 - 2 - 3
    

    它将充当某种委托方法。

    或者只是接受一个数组而不是参数?

    function funcA($params) 
    {
      extract($params);
    
      echo $a;
    }
    
    function funcB($params) 
    {
      extract($params);
    
      echo $a, $b;
    }
    
    function funcC($params) 
    {
      extract($params);
    
      echo $a, $b, $c;
    }
    
    
    $funcs = array('funcA', 'funcB', 'funcC');
    
    $selected = $funcs[0];
    
    
    $selected(array('a' => 'test', 'b' => 'test2'));
    
    // or something like  (beware of security issues)
    $selected($_GET);
    
        3
  •  -1
  •   Stijn Leenknegt    14 年前

    你不能,也许这是好事。您可以通过if/else找到参数的数量。

    如果($temp_call==“funca”)…..elseif(…)…

    推荐文章