Codeigniter中使用全局变量

Codeigniter中使用全局变量

本文介绍了如何在PHP Codeigniter中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在MVC应用程序中实现了登录逻辑;我想看看用户是否填写了用户名和passowrd不正确,如果是,我想在视图中显示一个通知;所以我通过$ data ['er'];但由于某种原因,它不会捕获此数据:

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

我的代码:

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

        }
    }

}


推荐答案

不要使用 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();
        }
    }
}

这篇关于如何在PHP Codeigniter中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:54