【问题标题】:zf2 pass multiple arguments in dynamic helper callzf2 在动态助手调用中传递多个参数
【发布时间】:2015-11-25 18:14:30
【问题描述】:

我正在尝试编写一个动态调用其他助手的视图助手,但我无法传递多个参数。以下场景将起作用:

$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 而没有传递给其他参数。

我不想在调用助手时发送多个参数,因为不同的助手接受不同数量的参数。我不想编写我的助手来将参数作为一个数组,因为整个项目其余部分的代码都使用谨慎的参数调用助手。

【问题讨论】:

    标签: php zend-framework2 view-helpers viewhelper


    【解决方案1】:

    你的问题是调用

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

    【讨论】:

    • 完美。就我而言,助手接收$args 作为逗号分隔的字符串,所以我不能动态编写$args = array('apple', 'bananas', 'oranges');。但是,使用$args = explode(",", $ args); 可以轻松实现数组转换。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-23
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 2013-08-14
        相关资源
        最近更新 更多