且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-07-31 05:14:15

不要使用 GLOBALS ,只要在类中使用私有变量即可。

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


  • __构造函数上创建 private $ er

  • __ contruct 函数中设置默认值

  • 设置并获取您的公共函数使用 $ this-> er

  • 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

p>

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