dongqing4774 2013-04-16 13:48
浏览 68
已采纳

在同一个类中存储和使用全局变量,但使用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.

  • 写回答

2条回答 默认 最新

  • dongyuqie4322 2013-04-17 09:08
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题