CodeIgniter: Where to Declare Global Variables

We use global variables in CodeIgniter so we can access it anywhere, be it in controller, model, or view.

There are several ways to declare global variables in CodeIgniter.

Table of Contents

Library

You can create your a file in application/libraries. Its class constructor contains an array as an argument. To use these variables you just have to autoload the newly created library.

constants.php

There is a file called constants.php where developers define constants. It is located at
application/config/constants.php. You can declare other types of variables in this file just fine.

//declare: 2 ways
$GLOBALS['expiration_date'] = '2019/05/07';
global $expiration_date;
$expiration_date = '2019/05/07';
//output
echo $GLOBALS['expiration_date'];
global $expiration_date;
echo $expiration_date;

Leave a Comment

Your email address will not be published. Required fields are marked *

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