视图页面中的未定义变量

时间:2012-11-01 12:11:05

标签: php codeigniter codeigniter-2

我无法在视图页面中传递变量

这是我的控制器代码

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Management extends CI_Controller {

        public function __construct()
       {
            parent::__construct();
            if($this->session->userdata('level') != 1){
                redirect('');
            } 
        }


        public function hotels()
        {   

                $this->load->model('model_hotels');

                $ss['most_view_hotels'] = '23';
                $this->load->view("management/header_mng_view");
                $this->load->view('management/hotels_mng_view' , $ss , true);
                $this->load->view("management/footer_mng_view");
        }

}

这是错误

  

遇到PHP错误

     

严重性:注意

     

消息:未定义的变量:most_view_hotels

     

文件名:management / hotels_mng_view.php

     

行号:22

hotels_mng_view.php

<?php 
  echo $most_view_hotels;
  foreach($most_view_hotels as $value):
?>
  <div class="row">
  <div class="cell en">adsf</div>
  <div class="cell en">1212</div>
  <div class="cell en">12</div>
  <div class="cell en">32</div>
  </div>
<?php endforeach;?>

4 个答案:

答案 0 :(得分:1)

在您的控制器中:

$ss['most_view_hotels'] = '23';
$this->load->view("management/header_mng_view");
$this->load->view('management/hotels_mng_view',$ss);
$this->load->view("management/footer_mng_view");

在您看来:

<?php echo $most_view_hotels?>

答案 1 :(得分:0)

在您的模板中,您将该项目称为......

$most_view_hotels

因此,我们需要在视图management/hotels_mng_view.php

中验证您正在执行的操作

答案 2 :(得分:0)

如Codeigniter手册所述:

There is a third optional parameter lets you change the behavior of the function
so that it returns data as a string rather than sending it to your browser.
This can be useful if you want to process the data in some way. If you set 
the parameter to true (boolean) it will return data. 
The default behavior is false, which sends it to your browser.

这意味着您的行

$this->load->view('management/hotels_mng_view' , $ss , true);

实际上将该视图的结果作为字符串返回给php,而不是将其发送到浏览器。

你的实际问题(未定义的变量)的答案依赖于management/hotels_mng_view.php,可能是一个错字。

答案 3 :(得分:0)

我认为问题在于第三个参数,即true

正如codeigniter文档所说:

There is a third optional parameter lets ..... 
Remember to assign it to a variable if you want the data returned

在您的代码中,您没有分配,将数据返回到任何代码。 我建议你尝试这样的事情:

public function hotels()
        {   

           $this->load->model('model_hotels');
           $data = array();
           $ss['most_view_hotels'] = '23';
           $data['header'] = $this->load->view("management/header_mng_view",,true);
           $data['body'] = $this->load->view('management/hotels_mng_view' , $ss , true);
           $data['footer'] = $this->load->view("management/footer_mng_view");
           $this->load->view("template",$data);
        }

 /*template view file*/
 <?php
    echo $header;
    echo $body;
    echo $footer;
 ?>

希望这有帮助。