axmug
axmug

Reputation: 466

Variable value in codeigniter views

I am trying to pass a variable from a controller to a view. I have some code but in order to understand what is the problem 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);
        }
    }

?>

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 $p value, I obtained the error:

ERROR

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?

Thanks.

Upvotes: 2

Views: 1185

Answers (2)

Rooneyl
Rooneyl

Reputation: 7902

First of variables need to be passed as an array (check out the docs).

$data = array(
               'title' => 'My Title',
               'heading' => 'My Heading',
               'message' => 'My Message'
          );

$this->load->view('welcome_message', $data);

$p has been declared out of 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));
}
}

Upvotes: 3

Mudshark
Mudshark

Reputation: 3253

You should declare $pin your controller's constructor:

class Welcome extends CI_Controller {

    function __construct() {
    parent::__construct();
        $this->p = 2;
    }

    public function index()
    {
        $data['p'] = $this->p;
        $this->load->view('welcome_message',$data);
    }
}

?>

Upvotes: 0

Related Questions