1

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). Zend must be doing something to prevent the array from being passed in by reference. Any ideas on a solution?

fronzee
  • 1,668
  • 2
  • 21
  • 32

2 Answers2

2

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. 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.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • That's very disappointing to discover, but understandable. (Btw, it's not really a "global" but I know what you mean.) – fronzee Dec 07 '11 at 00:09
  • See Zend_View_Abstract::_call(). It uses `call_user_func_array` to call your helper class. See [this question](http://stackoverflow.com/questions/8369851/variable-reference-as-function-argument/8370652#8370652). – nevvermind Dec 07 '11 at 07:48
1

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.

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.

Some people may have problems using $this->getHelper('Ref')->ref() instead of $this->ref() though, but it works.

nevvermind
  • 3,302
  • 1
  • 36
  • 45