在同一个类中存储和使用全局变量,但使用php的不同公共函数

在同一个类中存储和使用全局变量,但使用php的不同公共函数

问题描述:

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.

我有一个使用php进行netbeans的项目,我正在使用Zend框架,因此它是模型 - 视图 - 控制器。 p>

在一个类(newclassController)中,我有4个公共函数。 我想存储第二个函数的全局变量,并将其用于第4个函数 strong>。 p>

我试图将URL中的变量作为参数和SESSION变量发送,但是我遇到了一些错误,所以如果你有其他想法,请点击我。 p> \ n

我尝试过的所有返回都会显示以下错误消息:
注意:未定义的变量 code> p>

注意:如果我将变量存储在 init函数 code>,但我想从另一个函数存储它。 p> div>

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

public function__constructor(){
$this->value = 'something';
}

$this->value

will give 'something' in the class

decalre the variable in the constructor of the class and use it