0

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.

jcropp
  • 1,236
  • 2
  • 10
  • 29

3 Answers3

2

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);
ins0
  • 3,918
  • 1
  • 20
  • 28
  • Perfect. In my case, the helper receives `$args` as a comma-separated string, so I can't dynamically write `$args = array('apple', 'bananas', 'oranges');`. However, the array conversion is easily achieved with `$args = explode(",", $ args);`. – jcropp Nov 21 '15 at 22:07
1

For your case you can use the php function call_user_func_array since your helper is a callable and you want to pass array of arguments.

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

// Call function with callable and array of arguments
call_user_func_array($helper, $args);
Wilt
  • 41,477
  • 12
  • 152
  • 203
0

If you use php >= 5.6 you can use implement variadic function instead of using func_get_args().

Example:

<?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);
?>
mikicaivosevic
  • 157
  • 1
  • 7