0

All about a Zend Application with an action helper.

I want to unset some pairs of an array by a function.

helper:

class Application_Controller_Action_Helper_TestHelper extends Zend_Contr[...]
{    
    public function direct(&$array)
    {
        if(isset($array['key']))
            unset($array['key']);
    }
}

controller:

$this->_helper->TestHelper($var);

How could I get it working?

danijar
  • 32,406
  • 45
  • 166
  • 297
  • Your example of pass-by-ref should be working already. Isn't it? Please, explain the behavior you're getting... – Elias Dorneles Dec 03 '11 at 18:31
  • In my application I want the helper to unset some pairs of the array (parameter). It looks like: `public function direct(&$array){ if(isset($array['controller'])) unset($array['controller']); }` There is no error and no warning but the array is exactly the same like before. – danijar Dec 03 '11 at 18:41
  • I think the example you've given under "What I want is this" should work perfectly fine except that the left-hand side of the assignment `var = $var + 1` should read `$var` instead of just `var` – Abhay Dec 03 '11 at 18:58
  • @sharethis That's weird... Are you sure? Did you try `print_r()` the $array passed before and after the call to `direct()` to check? Could it be that, for example, the wrong key is being used in the `isset()` call in your real code? That would make it seem that the array isn't changing... (I tested the function you posted here, and for me the array changed.) – Elias Dorneles Dec 03 '11 at 18:59
  • @eljunior By testing i noticed that unset() unsets only the referenced array and not the real one. (_updated the main post with arrays_) – danijar Dec 03 '11 at 19:05

2 Answers2

2

Since you are now passing by reference, you can modify the variable in the method and the changes will be applied to the original variable. However, the way you have it now you are not changing the variable at all, just returning the result of the expression, like in your first example. You should have something like this instead:

class Application_Controller_Action_Helper_TestHelper extends Zend_Contr[...] {
    public function direct(&$var) {
        $var = $var + 1;
    }
}
rabusmar
  • 4,084
  • 1
  • 25
  • 29
0

You must also pass it as reference:
$this->_helper->TestHelper(&$var);

UPDATE: Ups, I had my errors turned off. You (and now me) are getting the error because...

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

ZF's HelperBroker uses return call_user_func_array(array($helper, 'direct'), $args); to call your direct() method. Check the docs, but it seems call_user_func_array passes by reference, although with several quirks.

Check out this answer.

Community
  • 1
  • 1
nevvermind
  • 3,302
  • 1
  • 36
  • 45