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.

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 Reply

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