Variable Reference as Function Argument

2019-09-05 23:37发布

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?

2条回答
2楼-- · 2019-09-05 23:45

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;
    }
}
查看更多
倾城 Initia
3楼-- · 2019-09-06 00:01

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.

查看更多
登录 后发表回答