Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter: global variables in a controller

Tags:

I'm a very newbie on CodeIgniter, and while I go on I run into problems that, in the procedural coding, were easy to fix

The current issue is: I have this controller

class Basic extends Controller {      function index(){         $data['title'] = 'Page Title';         $data['robots'] = 'noindex,nofollow';         $data['css'] = $this->config->item('css');         $data['my_data'] = 'Some chunk of text';         $this->load->view('basic_view', $data);     }      function form(){         $data['title'] = 'Page Title';         $data['robots'] = 'noindex,nofollow';         $data['css'] = $this->config->item('css');         $data['my_other_data'] = 'Another chunk of text';         $this->load->view('form_view', $data);     } } 

As you can see, some array items repeat over and over:

$data['title'] = 'Page Title'; $data['robots'] = 'noindex,nofollow'; $data['css'] = $this->config->item('css'); 

Isn't there a way to make them "global" in the controller, so that I have not to type them for each function? Something like (but this gives me error):

class Basic extends Controller {      // "global" items in the $data array     $data['title'] = 'Page Title';     $data['robots'] = 'noindex,nofollow';     $data['css'] = $this->config->item('css');      function index(){         $data['my_data'] = 'Some chunk of text';         $this->load->view('basic_view', $data);     }      function form(){         $data['my_other_data'] = 'Another chunk of text';         $this->load->view('form_view', $data);     }  } 

Thnaks in advance!

like image 769
Ivan Avatar asked May 14 '12 17:05

Ivan


People also ask

How declare variable in PHP CodeIgniter?

In CodeIgniter 4, we have a folder like app/config/Constant. php so you can define a global variable inside the Constant. php file. After your index.


1 Answers

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);     }  } 
like image 115
Rocket Hazmat Avatar answered Oct 19 '22 15:10

Rocket Hazmat