I’m trying to avoid this:
function do_something($arg1, $arg2, $arg3, $arg4, $arg5) {
function do_something_else($arg1, $arg2, $arg3, $arg4, $arg5) {
// code
}
do_something_else($arg1, $arg2, $arg3, $arg4, $arg5);
// do other things with the args
}
That is, repeating the args over and over especially in situations when there are a lot of args. In this example I need to have a nested function called do_something_else inside the main do_something function. The nested function also makes use of all the same args passed into it’s parent. So I must pass those into it and once more repeat all those args when actually executing the do_something function.
Is there a cleaner way to handle this? I know the built in php function func_get_args() returns an array of all the arguments inside a function but how to pass these into a child function so that they are available there as well, basically looking for a way to do this without repeating the args so many times?
You already said it. You can use
func_get_args()for simplicity. Combine it withcall_user_func_array()and you’re done:Actually there is a small caveat. This will only work in PHP 5.3 and onwards. Before that you need a temporary variable:
So, it’s not much more concise really. But it already shows the alternative: just refine your function signature to use arguments from an array instead.