将变量函数参数传递给PHP中的另一个函数

时间:2018-08-24 13:56:51

标签: php

我想将变量函数参数传递给一个函数foo,然后让foo将变量函数参数传递给另一个函数bar

同时,初始调用者还应该能够直接使用变量函数参数来调用bar

由于$args在到达foo时被转换为数组,因此不能作为变量函数参数传递,我该怎么做?

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");

2 个答案:

答案 0 :(得分:4)

只需将呼叫更改为#include <string> #include <iostream> #include <vector> int main() { std::vector<std::string> numbers {"3.14", "10", "t3", "toto"}; for (auto& nb : numbers) { bool correct = true; for (auto& c : nb) { try { std::stof(std::string(&c)); } catch(const std::exception&) { correct = false; break; } } if (!correct) { std::cout << "Cannnot convert [" << nb << "]\n"; } else { std::cout << "Correct conversion [" << nb << "]\n"; } } } 中的bar即可使用variable arguments。这样会将foo散布到各个参数中,然后再合并回到$args内部的数组中。

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");

答案 1 :(得分:0)

如果bar()不使用数组,则应传递$arg而不是$args

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