Store and use global variables in the same class, but different public functions using php

advertisements

I have a project made in netbeans with php and I am using Zend framework, so it's model-view-controller.

Into a class (newclassController), I have 4 public functions. I want to store a global variable from the second function and use it into the 4-th function.

I have tried to send the variable in the URL as a parameter and SESSION variables but I get some errors so if you have some other ideeas please enlight me.

All I tried returns gives this error message:
Notice: Undefined variable

NOTE: It works if I store the variable in the init function, but I want to store it from another function.


unless I miss my guess when you initiate a value in:

public function init(){
    $this->value = 'value';
}

the value is available to all of the 'actions' in the controller.

This is by design.

The init() method is used in ZF1 to supplement the constructor. It's where you add arguments that might normally be put in the constructor.

In order to persist a value from one action to another, some form of storage must be used.

For example:

//a verbose example
public function indexAction(){
    //initiate a variable
    $i = 100;
    //start a new session and assign a name to it
    $session = new Zend_Session_Namespace('number');
    //assign the value to the namespace
    $session->value = $i
}

later in that same controller or even another controller

public function newAction(){
    //access the session
    $session = new Zend_Session_Namespace('number');
    //assign the value to the view
    $this->view->value = $session->value;
}

now in the new.phtml view

<?php echo $this-value ?>

An important thing to remember when using PHP and specifically Zend Framework 1, every request runs the entire application.

This was a concept that tripped me up in the beginning. Every time you request a new page your Zend Framework application runs from scratch, so any data that needs to survive from one request to the next must be saved (persisted).