Welcome Guest, Not a member yet? Register   Sign In
Controller Class Variables
#1

[eluser]bennyhill[/eluser]
for my main controller, I have a bunch of reoccurring variables in each function in the class. For example,
Code:
$data['css'] = $this->config->item('css')
is declared in every function. I tried declaring the $data array variable at the top of the class, then populating it with the reoccurring values in the constructor but I get undefined variable errors for $css and $base in the view. Any advice on how to keep redundant variable definitions to a minimum in codeigniter?

example

Code:
class Catalog extends Controller{
   $data;
   function Catalog(){
      parent:Controller();
      $data = new array();
      $data['css'] = $this->config->item('css');
      $data['base'] = $this->config->item('base_url');
   }

   function index($v){
      $data['value'] = $v;
      $this->load->view('home', $data);
   }
}
#2

[eluser]gtech[/eluser]
Code:
class Catalog extends Controller{

   function Catalog(){
      parent:Controller();
      $this->data = new array();
      $this->data['css'] = $this->config->item('css');
      $this->data['base'] = $this->config->item('base_url');
   }

   function index($v){
      $this->data['value'] = $v;
      $this->load->view('home', $this->data);
   }
}
hello if you wish to use variables across functions within a class you can put $this-> in front of the variable so it becomes part of the controller object. Infact you dont even need to pass it to the view as you can access $this->data in the view once you have declared it.
#3

[eluser]Pascal Kriete[/eluser]
Small addition. You need to define it as a class variable.
Code:
class Catalog extends Controller{

    var $data;

   function Catalog(){
    ....
#4

[eluser]bennyhill[/eluser]
I tried your example multiple different ways to no success. All I get is a blank screen in the browser and when I view source there is nothing there. When I comment out the line
Code:
$this->data = new array();
out of the constructor the view loads fine. Any thoughts why nothing can be put in the constructor?
#5

[eluser]bennyhill[/eluser]
I got it. Just had to delete the line $this->data = new array(); For some reason I didn't need it.
#6

[eluser]phpworker[/eluser]
Gosh, but.... WAIT! The 'new' operator is not for array initialization, I suppose? Big Grin
#7

[eluser]nmweb[/eluser]
'new' only applies to objects and arrays are not objects in php unless you use spl in php5. Class properties in php4 are public so you can always access them, even from outside the object.
#8

[eluser]thinkigniter[/eluser]
Yep!

new Array(); is Javascript

php is just the plain and simple $var = array();
#9

[eluser]nmweb[/eluser]
It's a pity though that strings, integers and arrays etc. are not objects like they are in python. The syntax is way clearer + you extend types. I hope spl in php6 will solve this.




Theme © iAndrew 2016 - Forum software by © MyBB