7

I'm building a templating system and I'm running in to an issue with calling functions on the fly.

When I try the following:

$args = array(
    4,
    'test' => 'hello',
    'hi'
);

You know.. some numerical elements some associative elements,

call_user_func_array($function, $args);

converts the array to something like this:

$args = array(
    4,
    'hello',
    'hi'
);

Is there any way around this other than passing an array like this:

$args = array(
    4,
    array('test' => 'hello'),
    'hi'
);

Thanks! Matt

2
  • Can you show what is being done with $args in $function? Commented Mar 31, 2010 at 13:10
  • $function is just a string like 'to_lowercase' or something.. Commented Mar 31, 2010 at 13:21

1 Answer 1

19

There's nowhere for the array keys to go because:

call_user_func_array($function, $args);

is equivalent to this:

$function(4, 'hello', 'hi');

You could use call_user_func() instead:

call_user_func($function, $args);

then given a function with one argument, you can get the associative array:

function func($args) {
//    $args is complete associative array
}

Note that call_user_func() can also take more than one argument - each will be passed to the called function as an argument.

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

2 Comments

Oh really? I feel silly- I know I tried call_user_func() before deciding on call_user_func_array(), I guess my requirements must have changed. If I do func_get_args($args) will it return an array of the associative array?
yeah, func_get_args() == array($args) in the above example

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.