Why is $this->data not sending to view, but $data

2019-09-03 13:24发布

问题:

This is sending data to view in CodeIgniter:

    public function index()
    {           
        $data['header'] = "Home";
        $this->load->view('admin_frontpage', $data);
    }

And this is not:

    public function index()
    {
        $this->data['header'] = "Home";
        $this->load->view('admin_frontpage', $this->data);
    }

Why?

In my view file I try to echo:

    <?php echo $header; ?>

But only when using $data it is echoed. When using $this->data in controller, nothing is echoed out.

What am I doing wrong?

回答1:

Most likely is $this->data not defined.

You need to define a data member in your class

private $data;

and initialize it with

$this->data = array();

or all at once

private $data = array();

See Classes and Objects and Properties for details.



回答2:

$this->data is not defined in your controller. Remember the current page has no recollection of the name of the $data array. Every variable is instantiated as a seperate variable, just like when you are passing on the data array to 'admin_frontpage', the array is stripped out and every element of the array is instantiated as a variable (i.e. $this->data['header'] becomes $header)