简体   繁体   English

Zend Framework:通过引用传递给查看帮助程序不起作用

[英]Zend Framework: Pass by reference to view helper not working

Here is a simple view helper (notice the pass-by-reference argument): 这是一个简单的视图助手(请注意传递引用参数):

class Zend_View_Helper_MyViewHelper extends Zend_View_Helper_Abstract
{
  public function MyViewHelper(&$array)
  {
    unset($array['someExistingKey']);
  }
}

This does not work in the view. 这在视图中不起作用。 $array['someExistingKey'] is still set (except within the immediate context of the method). $array['someExistingKey']仍然被设置(方法的直接上下文中除外)。 Zend must be doing something to prevent the array from being passed in by reference. Zend必须做一些事情来防止数组被引用传递。 Any ideas on a solution? 关于解决方案的任何想法?

When you call $this->MyViewHelper($array) from your templates you are not actually calling the helper class directly, Zend_View is instantiating the class and calling it for you. 当您从模板中调用$this->MyViewHelper($array) ,您实际上并没有直接调用helper类,Zend_View会实例化该类并为您调用它。 So I think you might have trouble getting this working. 因此,我认为您可能无法正常工作。 Your best bet is probably to use Zend_Registry, or refactor to take a different approach not requiring a global. 你最好的选择可能是使用Zend_Registry,或者重构采用不需要全局的不同方法。

I just thought of a workaround. 我只是想到了一种解决方法。 You just have to call the helper manually, instead of letting ZF call it through call_user_func_array . 您只需要手动调用帮助程序,而不是让ZF通过call_user_func_array对其进行调用。

Ref.php Ref.php

class Zend_View_Helper_Ref extends Zend_View_Helper_Abstract
{
    public function removeFromRef(&$ref)
    {
        // change your var value here
        unset($ref['key']);
    }

    /**
     * ZF calls this for us, but we'll call what we want, so you can skip this.
     */
//    public function ref()
//    {}
}

As you can see, you can skip the convention of having to name your main method as the filename, but I still recommend it. 如您所见,您可以跳过必须将主方法命名为文件名的约定,但是我仍然建议这样做。 Now, you can pass references in views/controllers: 现在,您可以在视图/控制器中传递引用:

// in view:
$this->getHelper('Ref')->removeFromRef($someVar2Change);
// in controller
$this->view->getHelper('Ref')->removeFromRef($someVar2Change);

Basically, this is what $this->ref() does: gets the helper, then calls call_user_func_array . 基本上,这就是$this->ref()所做的:获取帮助器,然后调用call_user_func_array

Some people may have problems using $this->getHelper('Ref')->ref() instead of $this->ref() though, but it works. 有些人可能会使用$this->getHelper('Ref')->ref()而不是$this->ref()遇到问题,但是它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM