data __construct inside a controller

#1
[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!

#2
[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);
}

}

#3
[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(); ?

#4
[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');
}

}

#5
[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.

#6
[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);
}

}

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


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.