1

I have done quite some research, however most of the sources date very long back, so I am a bit confused as for how to do it in CI 3.x.

I have an application that is cloned for each and every user and runs independently from all the other instances. Every instances might be different in the way the calculate expenses and that is where the global variable comes in.

I have qucikly implemented the following solution:

*in application/config/config.php*

$config['expenses_calculation'] = 'monthly';

I can now acces the variable pretty much everywhere like this:

$this->config->config['expenses_calculation'];

However, I am new to CI and I believe that there has to be the right way for doing this and it is not the example provided by me.

Any hlep or guidance is much appreciated.

2 Answers 2

2

1. Define constants

application/config/constants.php

define('EXPENSES_CALCULATION', 'monthly');

Everywhere, where you need to access this:

print EXPENSES_CALCULATION; // output will be: "monthly"

2. Define variables in your controller

Controller:

class Page extends CI_Controller
{
    private $expenses_calculation = "";

    function __construct()
    {
        parent::__construct();

        $this->expenses_calculation = "monthly"; // you can fetch anything from your database or you do anything what you want with this variable
    }
}

The constructor of the controller always run before anything else (in the controller). So you can add any value to that "global" variable, and you can easy access this value everywhere from your controller.

print $this->expenses_calculation; // output will be: "monthly"
Sign up to request clarification or add additional context in comments.

Comments

1

If your intention is to provide a default \description of how to handle the calculation then what you have done is perfectly acceptable. I would suggest you access the variable in this way.

$calc_method = $this->config->item('expenses_calculation');

The advantage to this is that item('expenses_calculation') will return NULL if the item doesn't exist.

But if $this->config->config['expenses_calculation']; doesn't exist an "Undefined index" PHP error will be thrown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.