CodeIgniter - best place to declare global variable

J. Bruni picture J. Bruni · Jun 9, 2013 · Viewed 87.2k times · Source

I just want to use a $variable at several places: not only views and controllers, but also in the routes.php and other configuration files.

I don't want things like: use the Config class to load configuration files; use CI's get_instance, et cetera.

I just want to declare a given $variable (it could be a constant, but I need it as a variable), and use it absolutely everywhere.

In fact... I'd like to know which PHP file in the CI bootstrap is one of the first to be parsed, so I could introduce my global variable there... but not a core/system or inapproriated file, but the "best" suited placement for this simple requirement.

Answer

Dale picture Dale · Jun 9, 2013

There is a file in /application/config called constants.php

I normally put all mine in there with a comment to easily see where they are:

/**
 * Custom defines
 */
define('blah', 'hello mum!');
$myglobalvar = 'hey there';

After your index.php is loaded, it loads the /core/CodeIgniter.php file, which then in turn loads the common functions file /core/Common.php and then /application/constants.php so in the chain of things it's the forth file to be loaded.