如何在 PHP Codeigniter 中使用全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19237316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use global variable in PHP Codeigniter
提问by user385729
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:
我已经在 MVC 应用程序中实现了登录逻辑;我想看看用户是否错误地填写了用户名和密码,如果是,我想在视图中显示一个通知;所以我通过 $data['er'] 传递这些信息;但由于某种原因,它没有捕捉到这些数据:
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();
}
}
}
回答by doitlikejustin
Don't use GLOBALS
you can just use a private variable in your class.
不要使用,GLOBALS
您可以在类中使用私有变量。
- Create the variable above your
__construct
function likeprivate $er
- In your
__contruct
function set the default value - Set and get in your public function using
$this->er
- 在
__construct
函数上方创建变量,例如private $er
- 在您的
__contruct
函数中设置默认值 - 设置并使用您的公共功能
$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();
}
}
}