3

我正在尝试将变量从控制器传递到视图。我有一些代码,但为了理解问题是什么,我把它简单化了。这是我的控制器:

<?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);
        }
    }

?>

变量 p 在视图中声明。

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>
    <?php echo $p?>
</div>

当我尝试显示 $p 值时,我得到了错误:

错误

Parse error: syntax error, unexpected '$p' (T_VARIABLE), expecting function (T_FUNCTION) in C:\wamp\www\..\application\controllers\welcome.php on line 20

怎么了?

谢谢。

4

2 回答 2

3

首先需要将变量作为数组传递(查看文档)。

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

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

$p 已被声明超出函数的范围,所以要么;

public function index() {
   $p = 2;
   $this->load->view('welcome_message',array('p' => $p));
}

或者

class Welcome extends CI_Controller {

public $p=2;

public function index()
{
    $this->load->view('welcome_message',array('p' => $this->p));
}
}
于 2013-01-31T11:25:17.600 回答
0

您应该$p在控制器的构造函数中声明:

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);
    }
}

?>

于 2013-01-31T11:24:53.560 回答