0

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?

Derfder
  • 3,204
  • 11
  • 50
  • 85

2 Answers2

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.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • Do I need to put this code before the constructor in the controller? – Derfder Mar 08 '13 at 14:11
  • You can put it at the top of the index() method – Husman Mar 08 '13 at 14:14
  • @Derfder You can put this in your class definition before the `index()` method. – Olaf Dietsche Mar 08 '13 at 14:14
  • I get Parse error: syntax error, unexpected 'public' (T_PUBLIC) – Derfder Mar 08 '13 at 14:15
  • @Derfder Please see modified answer. It is better to make the `data` member `private`. – Olaf Dietsche Mar 08 '13 at 14:19
  • why is better to use private instead of public? It could be accessed from url or something? – Derfder Mar 08 '13 at 14:26
  • 1
    @Derfder If you make a member `private`, only methods belonging to the class can access and modify it. This encapsulates the state of the object and no method outside can accidentally modify it. See this question and answers http://stackoverflow.com/q/985298/1741542 and [Wikipedia - Information hiding](http://en.wikipedia.org/wiki/Information_Hiding) for more. – Olaf Dietsche Mar 08 '13 at 14:34
1

$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)

Husman
  • 6,819
  • 9
  • 29
  • 47