Global Variables in CodeIgniter not Working Global Variables in CodeIgniter not Working codeigniter codeigniter

Global Variables in CodeIgniter not Working


You cannot use the session library in config file.

The config files are loaded before any libraries, so $this->session is undefined.


The config.php has to be loaded in order for the Session class to even be initialized, as it reads settings from that file.

A lot of issues with this type of thing (setting some "global" data) can be resolved using a base controller, and extending it in your controllers.

// core/MY_Controller.phpMY_Controller extends CI_Controller {    function __construct()    {        parent::__construct(); // Now the Session class should be loaded        // set config items here     }}

"Normal" controllers will now extend MY_Controller to take advantage of this.

See: http://codeigniter.com/user_guide/general/core_classes.html for more details.

In addition, when you load->vars(), they are available to the view layer only, it does not create a global variable called $data as you seem to be trying to access. If you do this:

$this->load->vars(array('user' => '1'));

You would access it in a file loaded by $this->load->view() like this:

echo $user;  // outputs "1"

See: http://codeigniter.com/user_guide/libraries/loader.html

$this->load->vars($array)

This function takes an associative array as input and generates variables using the PHP extract function. This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might want to use this function independently is if you would like to set some global variables in the constructor of your controller and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached and merged into one array for conversion to variables.

I will say that as an experienced Codeigniter user, the concept of a "global vars" class is a bit wonky and probably unnecessary, especially when it's already so easy to get and set config items. You could definitely run into some confusing issues and variable name conflicts with this method (pre-loading lots of view variables on every request).