CodeIgniter Forums

Full Version: Assign data variable in the constructor?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Taff[/eluser]
Hey.
I'm passing a couple of variables to a view using

Code:
$this->load->view('default_view',$data);

of which one variable is a title

Code:
$data['title']="This is the title";

which works fine if I assign in the function (index() in this case)

but I would like to set a default title in the constructor (I think it's called the constructor)

Code:
class Task extends Controller {

    function Task()
    {
        parent::Controller();
        $this->load->model('/taskmodel','model');
        $data['title']="cool";
    }
    
    function index(){    
        $data['tasks']=$this->model->get_tasks($this->user_id,0);
                //Doesn't send $data['title'] to the view
        $this->load->view('tasks/default_view',$data);
    }
}

I would have expected it to work...but I expect everything to work until I try it.

Am I doing something wrong, is it not possible, or is there a workaround (I thought maybe $data['title']=$this->config->item("cool")Wink

Thanks for any help,
Taff

El Forum

[eluser]codedrunk[/eluser]
if you insist on having that value in the constructor then maybe try this:

Code:
class Tasks extends Controller {

   var data;

    function Tasks()
    {
        $this->data['title'] = 'Circus';
    }

    function index()
    {
        $this->data['other_var'] = 15;
        $this->load->view('view.php', $this->data);
    }

{

El Forum

[eluser]Taff[/eluser]
Great, thanks!
Quote:if you insist on having that value in the constructor
Wouldn't you assign that in the constructor if it is only going to change on a couple of occasions?

Cheers,
Taff

El Forum

[eluser]gtech[/eluser]
It makes sense to put variables in the constructor when you are sharing the variable across the class functions, if its scope is only within the function itself then it makes sense to put it in the function.

El Forum

[eluser]codedrunk[/eluser]
[quote author="Taff" date="1211054420"]Great, thanks!
Quote:if you insist on having that value in the constructor
Wouldn't you assign that in the constructor if it is only going to change on a couple of occasions?

Cheers,
Taff[/quote]

Yep. What i do is make it a config variable and then in my header I have this..

Code:
<title><?=$this->config->item('title').$extended_title;?></title>

It's suits my applications to just append whatever after the page title.

Cheers Smile

El Forum

[eluser]Taff[/eluser]
cool,
Cheers!