tags:

views:

94

answers:

1

Hey all,

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  A: 

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

call_user_func_array($function, $args);

becomes

$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.

Tom Haigh
nothing more to add. deleting mine, upvoting yours
Gordon
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?
Matt
yeah, func_get_args() == array($args) in the above example
Tom Haigh