0

可能重复:
PHP 可选参数 - 按名称指定参数值?

我有一个 assoc 数组,其中列出了对我来说是什么参数。这是一个例子:

array(
    'param1' => 'value1',
    'param4' => 'value4',
    'param3' => 'value3',
    'param2' => 'value2',
);

请注意,它们可能未排序。现在,有没有办法可以进行调用(静态或从实例,使用call_user_func_array或类似方法)并将每个值正确传递给每个参数?可以肯定的是,我想使用该参数数组调用的示例函数是这样的:

exampleFunction($param1, $param2, $param3, $param4) {
    ...
}

PS:反射很棒,但我担心执行时间(至少在Java中使用反射时会增加很多)。如果您知道任何其他方法可以做到这一点,那就太棒了。

4

2 回答 2

1

To avoid this problem you should pass an array as parameter, like the following.
This way you'll not be stacked in a specific order and you can set defaults for the parameters that are not in the array.

$data = array(
    'param1' => 'value1',
    'param4' => 'value4',
    'param3' => 'value3',
    'param2' => 'value2',
);

exampleFunction($data);

function exampleFunction($params= array()) {
    $defaults = array(
        'param1' => '1',
        'param4' => '2',
        'param3' => '3',
        'param2' => '4',
    );

    $params += $defaults;
}

You can access an array element by the following.

$data['param1'], $data['param2'], $data['param3'], ...
于 2012-12-12T16:51:26.267 回答
0

If you're just trying to call the function using the values from the parameters, then I think this is what you want to do:

exampleFunction($params['param1'], $params['param2'], $params['param3'], $params['param4']);

Arrays in PHP act as maps too, so you can just use it like that.

于 2012-12-12T16:51:42.160 回答