2015-11-18 39 views
0

我正在尝试编写一个动态调用其他助手的视图助手,并且我无法传递多个参数。下面的场景将工作:zf2在动态助手调用中传递多个参数

$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并没有给其他论点。

我不想在调用帮助器时发送多个参数,因为不同的帮助器采用不同数量的参数。我不想写我的助手把参数作为一个数组,因为整个项目的其余部分的代码都用谨慎的参数调用助手。

回答

2

您的问题是调用

$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); 
+0

完善。在我的情况下,助手接收'$ args'作为逗号分隔的字符串,所以我不能动态地写'$ args = array('apple','bananas','oranges');'。但是,数组转换很容易用'$ args = explode(“,”,$ args);'来实现。 – jcropp

1

对于你的情况,你可以使用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); 
0

如果您使用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); 
?>