PHP - 将来自func_get_args()的参数传递给函数,提示?

时间:2013-01-13 18:58:50

标签: php string function arguments

我有一个公共方法,用于在我的框架中创建名为addElement()的子元素,其定义如下:

// addElement - adds an element (experimental version)
public function addElement() {
    if ($arguments = func_get_args()) {
        $class = "\\UI\\{$arguments[0]}";

        if (func_num_args() > 1) {
            $parameters = null;

            foreach (array_slice($arguments, 1) as $argument) {
                $parameters[] = (is_numeric($argument) ? $argument : "\"{$argument}\"");
            }

            $this->elements[($arguments[0] === HTML ? uniqid() : $arguments[1])] = new $class(implode(", ", $parameters));
        }
    }
}

它被调用如下:

$article1 = new \UI\Article("article1");
$article->addElement(\UI\Aside, "aside1");

或者(取决于您是否需要直接访问新元素):

$article1 = new \UI\Article("article1");
$aside1 = $article->addElement(\UI\Aside, "aside1");

问题在我使用接受两个以上参数的方法(元素的类型及其名称,内部方式)时出现,就是这样:

$article1 = new \UI\Article("article1");
$article1->addElement(\UI\Abbreviation, "abbr1", "RAM", "Random Access Memory");

使用此方法,传递给函数的参数实际上是:

"abbr1", "RAM", "Random Access Memory"

我的意图是传递此字符串,就像通常将参数传递给给定函数一样。我该如何执行(如果我需要重新构造函数,那就没关系,虽然我最好只是添加缺少的位,如果这样做是正确的)?

1 个答案:

答案 0 :(得分:2)

当你得到一个类的实例时,你可以使用reflection,并传递一个参数数组,如下所示:

$ref = new ReflectionClass( $class);
$this->elements[($arguments[0] === HTML ? uniqid() : $arguments[1])] = $ref->newInstanceArgs( $parameters);

你也不需要这个:

$parameters = null;

foreach (array_slice($arguments, 1) as $argument) {
     $parameters[] = (is_numeric($argument) ? $argument : "\"{$argument}\"");
}

您可以使用上面的代码替换if语句的内容:

$parameters = array_slice( $arguments, 1);