CodeIgniter: global variables in a controller
What you can do is make "class variables" that can be accessed from any method in the controller. In the constructor, you set these values.
class Basic extends Controller { // "global" items var $data; function __construct(){ parent::__construct(); // needed when adding a constructor to a controller $this->data = array( 'title' => 'Page Title', 'robots' => 'noindex,nofollow', 'css' => $this->config->item('css') ); // $this->data can be accessed from anywhere in the controller. } function index(){ $data = $this->data; $data['my_data'] = 'Some chunk of text'; $this->load->view('basic_view', $data); } function form(){ $data = $this->data; $data['my_other_data'] = 'Another chunk of text'; $this->load->view('form_view', $data); }}
You can setup a class property named data and then set it's default values into the contructor which is the first thing which is run when a new instance on Basic
is created.Then you can reference to it with the $this
keyword
class Basic extends Controller{ var $data = array(); public function __construct() { parent::__construct(); // load config file if not autoloaded $this->data['title'] = 'Page Title'; $this->data['robots'] = 'noindex,nofollow'; $this->data['css'] = $this->config->item('css'); } function index() { $this->data['my_data'] = 'Some chunk of text'; $this->load->view('basic_view', $this->data); } function form() { $this->data['my_data'] = 'Another chunk of text'; $this->load->view('form_view', $this->data); }}
hey thanks here's my snipetit's a global variable holding a view
/* Location: ./application/core/MY_Controller */class MY_Controller extends CI_Controller { function __construct() { parent::__construct(); $this->data = array( 'sidebar' => $this->load->view('sidebar', '' , TRUE), ); }}/* Location: ./application/controllers/start.php */class Start extends MY_Controller { function __construct() { parent::__construct(); } public function index() { $data = $this->data; $this->load->view('header'); $this->load->view('start', $data); $this->load->view('footer'); }}