Search code examples
phpzend-framework2view-helpersviewhelper

zf2 pass multiple arguments in dynamic helper call


I'm trying to write a view helper that calls other helpers dynamically, and I am have trouble passing more than one argument. The following scenario will work:

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

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

However, I want to do something like this:

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

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

with this:

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

but it passes "apples, bananas, oranges" to $arg1 and nothing to the other arguments.

I don't want to have to send multiple arguments when I call the helper because different helpers take different numbers of arguments. I don't want to write my helpers to take arguments as an array because code throughout the rest of the project calls the helpers with discreet arguments.


Solution

  • Your problem is that calling

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

    will be interpreted as

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

    so you call the method with only the first param.


    To achieve you expected result look at the php function call_user_func_array. http://php.net/manual/en/function.call-user-func-array.php

    Example:

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