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.
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);
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);
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'."
",
$req, $opt, count($params));
}
f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>