Variable value in codeigniter views
I am trying to pass a variable from controller to view. I have some code, but in order to understand what the problem is, I made it simple. Here is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
$p=2;
public function index()
{
$this->load->view('welcome_message',$p);
}
}
?>
The variable p is declared in the view.
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<?php echo $p?>
</div>
When I try to display the value of $ p, I got the error:
MISTAKE
Parse error: syntax error, unexpected '$p' (T_VARIABLE), expecting function (T_FUNCTION) in C:\wamp\www\..\application\controllers\welcome.php on line 20
What's wrong?
Thank.
+3
source to share
2 answers
The first variables should be passed as an array ( check docs ).
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('welcome_message', $data);
$ p is declared outside the scope of the function, so either:
public function index() {
$p = 2;
$this->load->view('welcome_message',array('p' => $p));
}
or
class Welcome extends CI_Controller {
public $p=2;
public function index()
{
$this->load->view('welcome_message',array('p' => $this->p));
}
}
+3
source to share