Welcome Guest, Not a member yet? Register   Sign In
How to make variable global?
#1

[eluser]whygod[/eluser]
Hi guys,

How to make variable to be available/accessible across libraries, models, controllers etc...
In short make GLOBAL?

Thank you very much in advanced.
#2

[eluser]TheFuzzy0ne[/eluser]
You can use the [url="http://php.net/manual/en/language.variables.scope.php"]global[/url] keyword within your functions/methods, but that's not recommended.

If you want to access something globally, you can store it in the CI super object.

From your controller or models, for example:
Code:
// Set a variable.
$this->my_var = 'foo';

// Echo a variable value.
echo $this->my_var = 'foo';

or, from within libraries and helpers:
Code:
// Set a variable.
get_instance()->my_var = 'foo';

// Echo a variable value.
echo get_instance()->my_var;

You can also store values in a configuration file and use the config library to access it. It depends on what you want to store and why. In most cases, you can just pass whatever data you need into a function as a parameter. If you have too many variables cluttering the global namespace, you might end up running into problems.
#3

[eluser]Aken[/eluser]
If you think you need a global variable, you probably don't.
#4

[eluser]LifeSteala[/eluser]
This is when you should create a MY_Controller controller and extend it. Create a MY_Controller variable and your controllers can access it. Otherwise, consider storing it in a session.




Theme © iAndrew 2016 - Forum software by © MyBB