2

I'd like to pass variable function arguments to one function, foo, and then have foo pass the variable function arguments on to another function, bar.

At the same time, the initial caller should also be able to call bar directly with variable function arguments.

How can I do this, since $args is converted to an array when it reaches foo and thus can't be passed on as variable function arguments?

function bar($prefix, ...$args) {
  foreach($args as $arg)
    echo "bar: $prefix: $arg\n";
}

function foo($prefix, ...$args) {
  echo "Just passing through...\n";
  foreach($args as $arg)
    echo "foo: $prefix: $arg\n";
  bar($prefix, $args); // wrong, since $args is now an array
}

foo("Idefix", "FOO", "BAR");
bar("Obelix", "ABC", "DEF");
1
  • I do not agree. First, the question I linked was answered 2 years ago, with better quality answers. When future novice developers will search for an answer to this question they should stumble upon that question. Secondly, it is not about the context, but rather the clarity of the question and its answers. The context may make sense to you, but would other people also benefit from it? If you really do have something of value to add you can post a comment on the old question, but it is not recommended. Commented Aug 24, 2018 at 14:52

2 Answers 2

4

Just change the call to bar in foo to use variable arguments too. That spreads $args back out into individual parameters, which are then consolidated back into an array inside bar.

function bar($prefix, ...$args) {
  foreach($args as $arg)
    echo "bar: $prefix: $arg\n";
}
function foo($prefix, ...$args) {
  echo "Just passing through...\n";
  foreach($args as $arg)
    echo "foo: $prefix: $arg\n";
  bar($prefix, ...$args);
}

foo("Idefix", "FOO", "BAR");
bar("Obelix", "ABC", "DEF");

Output:

Just passing through...
foo: Idefix: FOO
foo: Idefix: BAR
bar: Idefix: FOO
bar: Idefix: BAR
bar: Obelix: ABC
bar: Obelix: DEF
Sign up to request clarification or add additional context in comments.

Comments

0

if bar() don't use array the you should pass $arg and not $args

  function foo($prefix, ...$args) {
    echo "Just passing through...\n";
    foreach($args as $arg)
      echo "foo: $prefix: $arg\n";
    bar($prefix, $arg); 
  } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.