I have a controller in CodeIgniter like this
class C extends CI_controller {
public function A()
{
var $data;
}
public function B(){
//here i need to access the variable $data;
}
}
How to do that in CodeIgniter? I can use a session. Is it really a good thing to assi开发者_运维问答gn that variable in a session? Is there any better way to declare the global varaibles?
i used like this but not working y
class C extends CI_controller {
public $data;
public function A()
{
$this->data=1;
}
public function B(){
//here $this->data showing null value y
}
}
Global variables only exist in the lifetime of the request. Since for one request there's only one function executed in the controller (or you doing it the wrong way!) global variables won't work.
You have to put it into session or in database.
Use CI's session helper:
class C extends CI_controller {
public function A()
{
$this->load->library('session');
$data = array('data'=>$data); //set it
$this->session->set_userdata($data);
}
public function B(){
$this->load->library('session');
$this->session->userdata('data'); //access it
}
}
You should try and set some variables on a config file then you just include that file on your controllers constructor and you can access these variables from any view you want... http://codeigniter.com/user_guide/libraries/config.html
The 2nd block of code you have will not work if you have this scenario: Enter page C/A then enter C/B. Once a page is done, you won't be able to use the values you stored in global variables.
Try using sessions or flashdata. Flashdata is similar to a session except it disappears after the next page call.
Here's the CI page for sessions and flashdata for reference: http://codeigniter.com/user_guide/libraries/sessions.html
精彩评论