CodeIgniter Forums
data __construct inside a controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: data __construct inside a controller (/showthread.php?tid=13771)



data __construct inside a controller - El Forum - 12-04-2008

[eluser]coolant[/eluser]
I'd like the ability to have $data be used in all of the methods automatically without having to define it in each method. This would be how I would do it in non-CI. I tried creating a method called Home and putting the $data['cow'] in there, but no such luck.

Also, can I use $this->load inside this "construct" ?

Code:
class Home extends Controller {

public $data;

function __construct()
{
  $data['cow'] = 'moo';
}

function foo()
{
  $this->load->view('foo', $data);
}

function bar()
{
  $this->load->view('bar', $data);
}

}

Thanks!


data __construct inside a controller - El Forum - 12-04-2008

[eluser]TomsB[/eluser]
Code:
class Home extends Controller {

function __construct()
{
  $this->data['cow'] = 'moo';
}

function foo()
{
  $this->load->view('foo', $this->data);
}

function bar()
{
  $this->load->view('bar', $this->data);
}

}



data __construct inside a controller - El Forum - 12-04-2008

[eluser]coolant[/eluser]
That will work if I just have data, but what if I have $this->load.

I get the obvious
Code:
Fatal error: Call to a member function file() on a non-object
with something like $this->load->file('test'); in the __construct.

Do I need to do something with $this->CI =& get_instance(); ?


data __construct inside a controller - El Forum - 12-04-2008

[eluser]TomsB[/eluser]
I have no errors when doing like this:
Code:
class Home extends Controller {

function __construct()
{
  $this->data['cow'] = 'moo';
  $this->load->file('test');
}

}



data __construct inside a controller - El Forum - 12-04-2008

[eluser]coolant[/eluser]
Try something like this -

Code:
class Home extends Controller {

function __construct()
{
  $this->data['cow'] = 'moo';
  $this->load->file('test');
}
    
function index()
{
   $this->load->view('home', $this->data);
}
    
}

You'll see the error I am talking about.


data __construct inside a controller - El Forum - 12-04-2008

[eluser]TomsB[/eluser]
I guess you need to add "parent::Controller();"
Code:
<?class Main extends Controller {

function __construct()
{
parent::Controller();
  $this->data['cow'] = 'moo';
  $this->load->file('test');
}

function index()
{
   $this->load->view('home', $this->data);
}

}



data __construct inside a controller - El Forum - 12-04-2008

[eluser]coolant[/eluser]
ah perfect! thx!