1

According to Code Igniter - best place to declare global variable, I can create global variables in Codeigniter.

I can add custom config variables also to config.php in Codeigniter.

What is the difference of above two methods? I mean, if I need to store some value in whole project wise, what method should I use?

Damith Ruwan
  • 338
  • 5
  • 18
  • Well you can always save some info in session variables!! ... or just add in Constants.php – TigerTiger Jun 30 '17 at 08:34
  • 1
    Set value as constant if it is not meant to be changed. If you want perform some action over that value returning different one, set it in config file. – Tpojka Jun 30 '17 at 09:20

1 Answers1

0

The main difference is that the value stored in config will need an extra step to read the value. If a var is defined in constants.php then it can be used directly.

In constants.php

$my_global = 'foo';

can be used directly

echo $my_global.'bar';  //outputs "foobar"

If the value is stored in config.php

$config['my_global'] = 'foo';

Then you have to read the value from config before you can use it.

$my_global = $this->config->item('my_global');
echo $my_global.'bar';  //outputs "foobar"

Or use the config retrieval directly

echo $this->config->item('my_global').'bar';  //outputs "foobar"

Constants are, by definition, a value that cannot change during the execution of the script. If that's what you need then define the value as a constant.

 define(MY_GLOBAL, 'foo');
 echo MY_GLOBAL.'bar';  //outputs "foobar"

If the value needs to change dynamically during script execution use config instead.

Both constants.php and the config library are loaded early in the framework's initialization and so are available for use when the controller is instantiated.

DFriend
  • 8,869
  • 1
  • 13
  • 26