php - Why is constructor not sending array to view?
383
I have something like this in my admin.php controller:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in_admin') )
{
redirect('admin/login');
}
$this->load->model('mdl_admin');
$data['my_test_variable'] = "This is test!";
}
public function index()
{
$data['header'] = "Home";
$this->load->view('admin_frontpage', $data);
}
And in my view this:
<?php echo $header; ?>
<?php echo $my_test_variable; ?>
But only header variable is echoed. Even if the $data array that is sent to the view file contains my_test_variable too.
Why is that?
What am I doing wrong?
Even if I try e.g.:
$this->data['my_test_variable'] = "This is test!";
it is not working.
Answer
Solution:
But the
$data
array that is sent to the view does not containmy_test_variable
too. In theindex()
function, you're not setting that value when sending it to the view.In
__construct()
,$data
is a local variable visible only within the__construct()
function. If you want to access it outside the function, maybe in theindex()
function, one option would be to make it an instance property.For example, instead of
$data['my_test_variable']
, you could use$this->data['my_test_variable']
, then, inindex()
, again, instead of$data
, you could use$this->data
.Answer
Solution:
Pass your data with view
try this....
Answer
Solution:
First of all, you're implicitly creating variables in PHP - which is bad practice. You shouldn't be setting array keys in variables that don't exist. With the proper error reporting settings enabled, this would be causing you problems.
So, first, let's fix that problem:
And, in doing that, I think you should be able to see your problem now. The
__construct()
andindex()
methods execute with a different stack. What that means is that the variables you declare inside of one are not available to the other. What you have to do in order to make this work is utilize an instance variable of the class you are creating, like this:And now you should get what you're after