【问题标题】:PHP: convert array to function argument listPHP:将数组转换为函数参数列表
【发布时间】:2015-04-02 03:56:23
【问题描述】:

是否可以通过某种方式将_call 中的数组转换为函数参数列表并让代码工作?

abstract class FooClass {

  protected function foo() {

    $args = func_get_args();

    $listIndex = 0;

    foreach ($args as $arg) {

      echo ++$listIndex . ": " . $arg . "\n";

    }

  }

}

class BarClass extends FooClass {

  public function __call($name, $arguments) {

    if (strcmp($name, 'foo') == 0) {

      $this->$name(list($arguments));

    }

    die("Unexpected method.");

  }

}

$barInstance = new BarClass;

$barInstance->foo("one", "two", "three", "four");

【问题讨论】:

  • 你考虑过call_user_func_array?php.net/manual/en/function.call-user-func-array.php
  • $this->$name(list($arguments)); -> $this->foo(list($arguments));对于这种情况? 'unexpected method' 总是会被命中
  • 如果你使用的是 PHP 5.6,你也可以使用variadics
  • 谢谢@didierc,正是我想要的。谢谢。
  • @Machavity,我认为 PHP 5.6 对于我正在寻找的东西来说太新了,有些服务器可能还不支持它,我不希望我的代码在上传后停止工作。但感谢您指出这一点。

标签: php call variadic-functions


【解决方案1】:

好的,事实证明,我所要求的是可能的。这是固定的代码:

abstract class FooClass {

  protected function foo() {

    $args = func_get_args();

    $listIndex = 0;

    foreach ($args as $arg) {

      echo ++$listIndex . ": " . $arg . "\n";

    }

  }

  protected function fooz() {

    echo "\nDone!\n";

  }

}

class BarClass extends FooClass {

  public function __call($name, $arguments) {

    if (in_array($name, array('foo', 'fooz'))) {

      call_user_func_array(array($this, $name), $arguments);

    } else {

      die("Unexpected method.");

    }

  }

}

$barInstance = new BarClass;

$barInstance->foo("one", "two", "three", "four");
$barInstance->fooz();

这是输出:

1: one
2: two
3: three
4: four

Done!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2010-11-28
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2019-04-10
    相关资源
    最近更新 更多