如何在PHP Codeigniter中使用全局变量

use*_*729 3 php codeigniter

我在MVC应用程序中实现了登录逻辑; 我想看看用户是否填写了用户名并错误地传递了passowrd,如果是,我想在视图中显示一个通知; 所以我通过$ data ['er']传递这些信息; 但由于某种原因,它没有捕获这些数据:

如果我的问题是否清楚,请告诉我; 如果需要澄清,请告诉我哪个部分含糊不清

我的代码:

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();

        }
    }

} 
Run Code Online (Sandbox Code Playgroud)

doi*_*tin 6

不要使用GLOBALS你可以在你的班级中使用私有变量.

  • __construct函数上面创建变量就像private $er
  • 在您的__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();
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)