Global vars in Codeigniter Module Class undefined

419 views Asked by At

I have the following piece of code in a codeigniter module controller:

class MyClass extends MX_Controller{
    public $description = "index";
    public function index(){
        global $description;
        echo $description;
    }
}

According to normal PHP rules and the PHP documentation, this should work. However, it doesn't.

If I leave out the global $description I get a notice about the variable being undefined, but with it in place it doesn't seem to return anything.

Why aren't global variables working in this case?

2

There are 2 answers

1
Muhammad Raheel On BEST ANSWER

You should do it like this instead of using global. This will work as you are in the scope of class so you need $this

class MyClass extends MX_Controller{
    public $description = "index";
    public function index(){
        echo $this->description;
    }
}
0
Suleman Ahmad On

You can set variables in this way:

$this->load->vars($global_variables_array);

where $global_variables_array is an associative key value pair array, description is:-

This function takes an associative array as input and generates variables using the PHP extract function. This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might want to use this function independently is if you would like to set some global variables in the constructor of your controller and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached and merged into one array for conversion to variables.

here is link