1

I want to be able to call a php function, but only if the number of elements input, matches the number of elements accepted by the function and if it does match i want to pass them 1 by 1 and not as an array.

Currently i have the following code which does the job, but is messy.

call_user_func($functionname, $vars);

This was hitting problems when i had a function that expected an array of 4 elements, but was only passed 3. Having to check and make sure all the vars exist makes writing functions a bit messy. I have a better solution based on reflection. how to dynamically check number of arguments of a function in php , but im one final step short. If the number of arguments matches the number of arguments in a function, i can call that method, but i dont know how to call that method correctly. I have an array of variables. I need to pass these into the function so that I can do something like the following.

function foo($var1, $var2, $var3)
{
    //I know all 3 vars exist and dont need to verify first
}
if(count($arrayof3elements) == get_method_var_count("foo") {
    dynamically_call_method("foo", $arrayof3elements);
}
1
  • call_user_func_array accepts an array as a 2nd argument but passes them in to the function as separate parameters (as you want). Commented May 13, 2016 at 14:49

1 Answer 1

2

Instead of using call_user_func, use call_user_func_array - this allows you to pass an array of arguments, but passes them to the method as separate things.

function x($foo, $bar) {
    echo $foo . $bar;
}

call_user_func_array('x', ['abc', 'def']); // prints abcdef
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.