Where to Declare Global Variables in CodeIgniter

In PHP, global variables are variables that are available in all scopes throughout a program. They allow us to access essential information from anywhere in the code, making them essential for large projects.

A way to make your variables globally accessible is by adding variables to the constants.php file in the application’s config folder that contains any type of constant you need, like colors or strings for menu items!

These global variables give us the ability to use the same data throughout our application without having to repeatedly declare it in each individual controller, model, or view. In addition, global variables help to keep our code DRY (Don’t Repeat Yourself). This is good coding practice as it helps to make our code more readable and maintainable.

//add variables to application/config/constants.php
$GLOBALS['primaryColor'] = '#FF00F0';

global $appName;
$appName= 'Color Picker';

After that, you can call them in any files with:

echo $GLOBALS['primaryColor'];

global $appName;
echo $appName;

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close