Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Igniter 2.0 variable in constructor

Tags:

codeigniter

I have a small codeigniter controller. Below is the code

class Example extends CI_Controller {
    /*
     * Constructor function
     */

    function __construct() {
        parent::__construct();
        $data['extraScripts'] = 'test'; //Use to add extra scripts in head


    }

    function function1() {
      $this->load->view('v1',$data);

    }

    function function2() {
      $data['extraScripts'] = 'extraScript Veriable override here'; 
      $this->load->view('v2',$data);
    }

What I want is to define a veriable $data['extraScripts'] in Constructor of Controller and want that veriable in every method of that controller by default. I mean in function f1 I am not creating extraScripts variable but its view should take value from constructor(or from anyother method) and should not give me undefine variable error. In second function f2 I am overridding extraScript variable so its view should display that overrided text. Is that possible.

like image 295
Far Sighter Avatar asked Jan 24 '12 10:01

Far Sighter


1 Answers

Make $data an attribute (basic OOP).

For example;

class Example extends CI_Controller {
    /*
     * Constructor function
     */

    public $data = array();

    function __construct() {
        parent::__construct();
        $this->data['extraScripts'] = 'test'; //Use to add extra scripts in head


    }

    function function1() {
      $this->load->view('v1',$this->data);

    }

    function function2() {
      $data['extraScripts'] = 'extraScript Veriable override here'; 
      $this->load->view('v2',$this->data);
    }
}
like image 100
Rooneyl Avatar answered Nov 19 '22 02:11

Rooneyl