Welcome Guest, Not a member yet? Register   Sign In
Global variable in overrided Controller
#1

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.
Reply
#2

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)
Reply
#3

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
{
 
   public $data;

 
  //all the rest


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
{
 
   public $data;

 
   public function sayhi($name "World")
 
   {
 
       $this->data $name;
 
       $this->load->model('test_model');
 
       $data['name'] = $this->test_model->get_name();
 
       $this->load->view('test_view'$data);
 
   }


Model
PHP Code:
class Test_model extends CI_Model
{
 
   public function get_name()
 
   {
 
       return $this->data;
 
   }


The view
PHP Code:
<!DOCTYPE html>
<
html>
 
   <head>
 
       <title>Testing 1 2 3</title>
 
   </head>
 
   <body>
 
       <?= "Hello $name"?>
    </body>
</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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB