CodeIgniter - best place to declare global variable
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.
Solution 1:
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.
Solution 2:
I use a "Globals" class in a helper file with static methods to manage all the global variables for my app. Here is what I have:
globals_helper.php (in the helpers directory)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Application specific global variables
class Globals
{
private static $authenticatedMemberId = null;
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$authenticatedMemberId = null;
self::$initialized = true;
}
public static function setAuthenticatedMemeberId($memberId)
{
self::initialize();
self::$authenticatedMemberId = $memberId;
}
public static function authenticatedMemeberId()
{
self::initialize();
return self::$authenticatedMemberId;
}
}
Then autoload this in the autoload.php file
$autoload['helper'] = array('globals');
Lastly, for usage from anywhere within the code you can do this to set the variables:
Globals::setAuthenticatedMemeberId('somememberid');
And this to read it:
Globals::authenticatedMemeberId()
Note: Reason why I left the initialize calls in the Globals class is to have future expandability with initializers for the class if needed. You could also make the properties public if you don't need any kind of control over what gets set and read via the setters/getters.
Solution 3:
You could also create a constants_helper.php file then put your variables in there. Example:
define('MY_CUSTOM_DIR', base_url().'custom_dir_folder/');
Then on your application/config/autoload.php, autoload your contstants helper
$autoload['helper'] = array('contstants');
Solution 4:
inside file application/conf/contants.php :
global $myVAR;
$myVAR= 'http://'.$_SERVER["HTTP_HOST"].'/';
and put in some header file or inside of any function:
global $myVAR;
$myVAR= 'some value';