简体   繁体   中英

How to use global variable in PHP Codeigniter

I have implemented the login logic in an MVC application; I want to see if the user has filled the username and passowrd incorrectly and if so I want to show a notifictaion in the view; so I'm passing this information via $data['er']; but for some reason it is not catching this data:

Please let me know if my question is clear or not; and if any clarification is needed, please let me know which part is ambiguous

My code:

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

        }
    }

} 

Don't use GLOBALS you can just use a private variable in your class.

  • Create the variable above your __construct function like private $er
  • In your __contruct function set the default value
  • Set and get in your public function using $this->er

Implemented in your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM