Codeigniter控制器中的动态全局变量

时间:2017-05-17 06:52:54

标签: php codeigniter

我正在尝试在我的网站上添加一个动态标题,所以就在这里。

class Survey extends MY_Controller {

   public $my_title;

   public function __construct(){
     parent::__construct();
     $this->load->model('Survey_model');
     $this->my_title = ""; //setting to blank
   }

   public function survey_form(){
     $this->data['title']    = $this->my_title; //display the title
     $this->middle       = 'Survey_view';
     $this->layout();
   }

   public function validate_stub($survey_code){
     $data          = $this->Survey_model->get_questions($survey_code);
     $this->my_title    = $this->Survey_model->get_quest_title($survey_code); //getting from database title 

     $this->session->set_userdata('stub_data', $data);
     redirect('Survey/survey_form');
   }
}

第一个触发的是validate_stub函数,然后我想将get_quest_title的返回值传递给全局变量$ my_title,然后将其传递给survey_form函数。在这种情况下,$ this-> my_title为空,我如何从db传递标题然后放入全局变量然后传递给视图。感谢

1 个答案:

答案 0 :(得分:3)

我无法理解您在redirect中使用validate_stub()的原因。您可以直接调用survey_form函数,代码为:

class Survey extends MY_Controller {

   public $my_title;

   public function __construct(){
     parent::__construct();
     $this->load->model('Survey_model');
     $this->my_title = ""; //setting to blank
   }

   public function survey_form(){
     $grab_title = $this->session->userdata('my_title');
     if(isset($grab_title) && $grab_title != "") {
         $this->data['title']    = $grab_title;
     }else {
         //do some checks here and add something default
         $this->data['title']    = $this->my_title;             
     }
     $this->middle       = 'Survey_view';
     $this->layout();
   }

   public function validate_stub($survey_code){
     $data          = $this->Survey_model->get_questions($survey_code);
     $this->my_title    = $this->Survey_model->get_quest_title($survey_code); //getting from database title 

     $this->session->set_userdata('stub_data', $data);
     $this->session->set_userdata('my_title', $this->my_title);
     redirect('Survey/survey_form');
   }
}