Global variable in overrided Controller |
I override the CI_Controller with MY_Controller. It works fine (now) and I wonder if I can create a variable that would be accessible everywhere else in the project (Controllers, Models, Views, Libraries ...)
Sessions will do the job but will not be the best options, since variables will be keep from one page to another.
Hello imabot,
You can create a class (for example "Global") that you put where you want (for example "./application/utils/") In this class, you create some static variables (for example "$var1") Then, you add some few lines at the end of your index.php file using the spl_autoload_register function Finally, you can use your "global" variables like this: Global::$var1 everywhere you want (don't forget to put "use utils\Global" at the beginning of your file)
Any public property in the controller is easily accessed just about anywhere. Take the property "$data" in the following example.
PHP Code: Class Welcome extends CI_Controller You can get the value of $data everywhere in the controller using $this->data. It's also available anywhere you can get a reference to the controller. In models, you can still use $this. Here's a proof of concept. (It's dumb, I know. But it demos the point.) PHP Code: Class Welcome extends CI_Controller Model PHP Code: class Test_model extends CI_Model The view PHP Code: <!DOCTYPE html> Send a browser to example.com/welcome/sayhi/Dave and the screen displays "Hello Dave" If you want to get at the controller from a custom library you have to do the same thing that the core libraries do - use get_instance(); You've probably already read about that here. |
Welcome Guest, Not a member yet? Register Sign In |