Persisting Zend controller variables whilst forwarding actions

Quick tip for when you’re trying to persist variables in a controller using Zend Framework, if you’re using a class property for your action controller then it’s because using the _forward action helper will actually re-instantiate the controller class, so your member variables (properties) will be reset.

Thus if you declare them static then they will persist between _forward actions!

class SomethingController extends Zend_Controller_Action
{

    //protected $_someObject;
    protected static $_someObject;

public function indexAction()
{
    //$this->_someObject = new Model_SomeObject();
    self::$_someObject = new Model_SomeObject();

    $this->_forward('some');
}

public function someAction()
{
    //$this->view->someObject = $this->_someObject;
    $this->view->someObject = self::$_someObject;
}

}

Add comment