Welcome Guest, Not a member yet? Register   Sign In
Passing Data from Constructor to Method
#1

[eluser]Unknown[/eluser]
I'm new to CodeIgniter and I'm creating a login-protected site that follows this logic to verify a login:

__constructor()

- Check if the user's ID is stored in the session.
- If so, make sure they are a valid user (need this data anyway on the page).
- If neither check passes, redirect to login.

In an effort to reduce the number of queries performed, I wanted to find a way to start building my $data array early. Just doing this doesn't seem to work:

Code:
function __constructor() {
    $data = array('Foo');
}

function method() {
    array_push($data, 'Bar');
}
No problem, doing this seems to:

Code:
function __constructor() {
    // Get user data.
    $this->data = array('Foo');
}

function method() {
    array_push($this->data, 'Bar');
    $this->data['test'] = TRUE;
    // Pass user data and the above to a view.
    $this->load->view('page-template', $this->data);
}
My question is what danger, if any, is there in doing this?
#2

[eluser]summery[/eluser]
Hi pgoneill!

I think what you're doing is probably fine, but to be safe I would use $this->load->vars instead of creating your own $this->data variable.

$this->load->vars is terrific - not only does it make data in the constructor available in your controller, it also makes it automatically available to all views. It's a life-saver if you have a bunch of nested views, because that way you don't have to pass zillions of $data arrays to all of your partial views. Just give everything a good name in your $load->vars array and you're good to go.

Read more about $this->load->vars in the Loader Class documentation.

Good luck!
~S




Theme © iAndrew 2016 - Forum software by © MyBB