Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - best place to declare global variable

Tags:

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.

like image 993
J. Bruni Avatar asked Jun 09 '13 19:06

J. Bruni


People also ask

Where should I declare global variables?

You can declare global—that is, nonlocal—variables by declaring them outside of any function definition. It's usually best to put all global declarations near the beginning of the program, before the first function. A variable is recognized only from the point it is declared, to the end of the file.

Where are PHP global variables stored?

PHP stores all global variables in an array called $GLOBALS[index].

What is difference between global and GLOBALS in PHP?

They are two different things. global is a keyword which tells that the variable is from a global scope. E.g. if you're about to access a variable inside a function that's defined outside you'll need to use the global keyword to make it accessible in the function. $GLOBALS is a superglobal array.


1 Answers

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.

like image 143
Dale Avatar answered Oct 04 '22 00:10

Dale