Accessing the value of the public variable in the codeigniter controller

Does anyone know how to access the value of an open controller variable that has been updated by another function? sample code controller

class MyController extends CI_Controller { public $variable = array(); function __construct() { parent::__construct(); } function index(){ $this->variable['name'] = "Sam"; $this->variable['age'] = 19; } function another_function(){ print_r($this->variable); } 

}

when I call another_function (), I get an empty array. What could be the problem? Any help would be appreciated.

+7
source share
2 answers

you need to use the constructor instead of index ().

  class MyController extends CI_Controller { public $variable = array(); function __construct() { parent::__construct(); $this->variable['name'] = "Sam"; $this->variable['age'] = 19; } function index(){ } function another_function(){ print_r($this->variable); } } 

If you want to call index() , then call another_function() , try using the CI session class.

  class MyController extends CI_Controller { public $variable = array(); function __construct() { parent::__construct(); $this->load->library('session'); if ($this->session->userdata('variable')) { $this->variable = $this->session->userdata('variable'); } } function index(){ $this->variable['name'] = "Sam"; $this->variable['age'] = 19; $this->session->set_userdata('variable', $this->variable); } function another_function(){ print_r($this->variable); } } 
+9
source

The index() function is called only when going to this particular page, i.e. index.php/mycontroller/index , so going to index.php/mycontroller/another_function will not call the index() function. If you need the user to go to the index page first (to get information), first send them there and save the data in a database or in a session variable. If you know the values ​​in advance (that is, there will always be "Sam" and "19", then put this code in the constructor, which is called every time you visit the page from this controller.

+2
source

All Articles