开发者

Dynamic functions, variable inputs

开发者 https://www.devze.com 2023-01-07 12:44 出处:网络
Right now, lets say I have code much like this... $some_var=returnsUserInput(); function funcA($a) {...}

Right now, lets say I have code much like this...

$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开发者_C百科[$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);

My problem starts here, how can I specify the proper variables into the arguments depending on these? I have a few thoughts such as creating a list for each function that specifies these, but I would really like to see an elegant solution to this.


You need to use call_user_func or call_user_func_array.

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


You want something like the following?

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

It'd act as some sort of delegation method.

Or what about just accepting an array rather than paramaters?

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


You can't and maybe that's good to. You can find the amount of arguments with if/else.

if($temp_call == "funcA") { .....} elseif(...)...

0

精彩评论

暂无评论...
验证码 换一张
取 消