MightyPork
MightyPork

Reputation: 18861

How to proxy a varargs function in PHP

I'd like to "proxy" a varargs function (kinda like a shortcut):

/** The PROXY function */
function proxy_to_foo(/*varargs*/)
{
    real_foo(func_get_args());
}

/** The real function */
function real_foo(/*varargs*/)
{
    print_r(func_get_args());
}

// Now I call it:
proxy_to_foo(1, 2, 3);

But I get this (obviously):

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

Whereas this was the intention:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

How to fix it? Some weird reflection magic?

Upvotes: 3

Views: 564

Answers (2)

u_mulder
u_mulder

Reputation: 54841

Use call_user_func_array:

/** The PROXY function */
function proxy_to_foo(/*varargs*/)
{
    call_user_func_array('real_foo', func_get_args());
}

If your php is 5.6 and higher use variadic function arguments:

function proxy_to_foo(...$args) 
{
    real_foo(...$args);
}

function real_foo(...$args)
{
    print_r($args);
}

Upvotes: 4

Adam Sinclair
Adam Sinclair

Reputation: 1649

Alternatively, in this case:

function proxy_to_foo(/*varargs*/)
{
    real_foo(func_get_args());
}

function real_foo(/*varargs*/)
{
    print_r(iterator_to_array(new RecursiveIteratorIterator(
    new RecursiveArrayIterator(func_get_args())), FALSE));
}

proxy_to_foo(1, 2, 3);

Upvotes: 0

Related Questions