2013-10-08 73 views
2

我已經在MVC應用程序中實現了登錄邏輯;我想看看用戶是否填寫了錯誤的用戶名和密碼,如果是的話,我想在視圖中顯示一個通知;所以我通過$ data ['er']傳遞這些信息;但由於某種原因,它不能捕捉到這些數據:如何在PHP中使用全局變量Codeigniter

如果我的問題是否清楚,請讓我知道;如果需要澄清,請讓我知道哪一部分是曖昧

我的代碼:

class Login extends CI_Controller { 

    public function __construct() { 
     parent::__construct(); 
     $GLOBALS['er'] = False; 
    } 



    public function index() { 

     $data['er']=$GLOBALS['er']; 
     $data['main_content'] = 'login_form'; 
     $this->load->view('includes/template', $data); 
    } 

    public function validate_credentials() { 

     $this->load->model('user_model'); 
     $query = $this->user_model->validate(); 
     if ($query) { 
      $data = array(
       'username' => $this->input->post('username'), 
      ); 
      $this->session->set_userdata($data); 
      redirect('project/members_area'); 
     } else { 
      $GLOBALS['er'] = TRUE; 
      $this->index(); 

     } 
    } 

} 

回答

6

不要使用GLOBALS你可以只使用一個私有變量在你的類。

  • 創建變量像上面這樣private $er
  • __construct功能在你__contruct功能設置默認值
  • 集並採用$this->er

在你的代碼中實現你的公共職能得到:

class Login extends CI_Controller { 

    private $er; 

    public function __construct() { 
     parent::__construct(); 
     $this->er = FALSE; 
    } 

    public function index() { 
     $data['er']= $this->er; 
     $data['main_content'] = 'login_form'; 
     $this->load->view('includes/template', $data); 
    } 

    public function validate_credentials() { 
     $this->load->model('user_model'); 
     $query = $this->user_model->validate(); 
     if ($query) { 
      $data = array(
       'username' => $this->input->post('username'), 
      ); 
      $this->session->set_userdata($data); 
      redirect('pmpBulletin/members_area'); 
      //die(here); 
     } else { 
      $this->er = TRUE; 
      $this->index(); 
     } 
    } 
}