gruner
gruner

Reputation: 1570

Passing a function's args straight to another function

In PHP, is there a way to send a function's arguments straight to another function without having to specify them one by one? Is there a way to expand func_get_arg() so that the other function receives the individual arguments and not just a single array?

I'd like to send the arguments from foo() straight to bar() like so:

function foo($arg1, $arg2, $arg3)
{
  $args = expand_args(func_get_arg());
  bar($args);
}

Upvotes: 2

Views: 171

Answers (2)

Dean Rather
Dean Rather

Reputation: 32374

If you want to call it on a function belonging to an instance of an entirely seperate class, that can be done by passing the first arg to call_user_func_array as an array.

In this example, the function foo accepts whatever arguments, and passes them directly into $bar->baz->bob(), and returns the result.

public function foo(/* example arguments */)
{
    return call_user_func_array
    (
        array($bar->baz, 'bob'),
        func_get_args()
    );
}

Upvotes: 0

Byron Whitlock
Byron Whitlock

Reputation: 53850

yes.

function foo($arg1, $arg2, $arg3)
{
    $args = func_get_arg();

    call_user_func_array("bar",$args);

}

Upvotes: 5

Related Questions