zf2 在动态助手调用中传递多个参数

zf2 pass multiple arguments in dynamic helper call

我正在尝试编写一个动态调用其他助手的视图助手,但我在传递多个参数时遇到了问题。以下场景将起作用:

$helperName = "foo";
$args = "apples";

$helperResult = $this->view->$helperName($args);

但是,我想做这样的事情:

$helperName = "bar";
$args = "apples, bananas, oranges";

$helperResult = $this->view->$helperName($args);

有了这个:

class bar extends AbstractHelper
{
    public function __invoke($arg1, $arg2, $arg) 
    {
        ...

但是它将 "apples, bananas, oranges" 传递给 $arg1 而没有传递给其他参数。

我不想在调用助手时发送多个参数,因为不同的助手接受不同数量的参数。我不想编写我的助手来将参数作为数组,因为整个项目的其余部分的代码都使用谨慎的参数调用助手。

你的问题是调用

$helperName = "bar";
$args = "apples, bananas, oranges";

$helperResult = $this->view->$helperName($args);

将被解释为

$helperResult = $this->view->bar("apples, bananas, oranges");

所以你只用第一个参数调用方法。


要获得预期结果,请查看 php 函数 call_user_func_arrayhttp://php.net/manual/en/function.call-user-func-array.php

示例

$args = array('apple', 'bananas', 'oranges');
$helperResult = call_user_func_array(array($this->view, $helperName), $args);

对于您的情况,您可以使用 the php function call_user_func_array,因为您的助手是可调用的,并且您想传递参数数组。

// Define the callable
$helper = array($this->view, $helperName);

// Call function with callable and array of arguments
call_user_func_array($helper, $args);

如果您使用 php >= 5.6,您可以使用实现可变参数函数而不是使用 func_get_args()。

示例:

<?php
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>