2015-11-18 35 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); 
?>