0

Clearly this is really poor code, but I can't think how to improve it. The 'test' function can't be changed at all, but all the rest can.

I want to pass an array of values to one function that actions the test function. The key thing is I need to make use of all pre-defined function variable values in the test function without redeclaring them.

I can't action the test function directly, it must go through another function.

This is just a demo of a much bigger problem, but solving this will definitely solve my problem. If it can't be done I need to completely re-think many things.

function test($p1, $p2="hello", $p3=5, $p4=true) {

}

--

function action($vars = array()) {

    $count = count($vars);

    switch($count) {

        case 1:
            $result = test($vars[0]);
            break;
        case 2:
            $result = test($vars[0], $vars[1]);
            break;
        case 3:
            $result = test($vars[0], $vars[1], $vars[2]);
            break;
        case 4:
            $result = test($vars[0], $vars[1], $vars[2], $vars[3]);
            break;

    }

    return $result;

}

--

action(array(1, "test"));
2
  • 1
    It isn't even valid PHP. There are no case keywords in the switch Commented Mar 30, 2013 at 23:08
  • 1
    You are looking for call_user_func_array(). Commented Mar 30, 2013 at 23:08

2 Answers 2

5
call_user_func_array('test', $vars);

http://php.net/call_user_func_array

Sign up to request clarification or add additional context in comments.

1 Comment

Now if only @mario would have sent this an an answer and not a comment :/
0

You don't need to use "action" function, you can just use the "test" function alone with the help of func_get_args() php function. You don't need to pass an array as arguments, you can call your "test" function with arbitrary number of arguments. You may also take a look at func_get_arg() and func_num_args() functions in php.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.