变量通过但异常仍然抛出?

时间:2012-12-09 01:25:20

标签: php codeigniter

我创建并传递数据数组:

public function home()
{


    $data['page'] = 'home';
    $data['table'] = 'pageData';
    $data['temp'] = 'temp_1';

    $this->template($data);


}


    public function template($data)
{

    $this->load->model("model_get");


    $data['results'] = $this->model_get->getData($data);

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


}

这是模板视图:

<?php

$this->load->view('header');

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

$data['results'] = $results;

$this->load->view($temp, $data);

$this->load->view('footer');

?>

它会在以下位置抛出未定义变量的异常:

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

但仍然加载视图并完成其中的所有if语句,并从$temp中存储的名称加载视图。

为什么抛出异常?

1 个答案:

答案 0 :(得分:0)

您尚未在该视图中填充$ data以加载第二个视图。你的代码命名过于模糊,无法真正理解它应该做什么,但让我们分解它。

public function home()
{
$data['page'] = 'home';
$data['table'] = 'pageData';
$data['temp'] = 'temp_1';
$this->template($data);
}


public function template($data)
{
$this->load->model("model_get");
$data['results'] = $this->model_get->getData($data);
//I assume getData takes a table name and returns all the data
//This only works because you're taking all the data passed from the first function
//in the function above.
$this->load->view('template', $data);
}


<?php
$this->load->view('header');
$this->load->view('nav', $data);
//At this point $data is empty. You have available $results, $page, $table and $temp
//because they were passed from the template function above.
$this->load->view('nav', $results);
//The line above is what it appears you need, rather than $data.
$data['results'] = $results;
//You've repopulated $data here but now all it contains is $results.
$this->load->view($temp, $data);
$this->load->view('footer');
?>

你误解的是$ data不是持久性的,当你通过加载一个带有$ data的视图作为第二个参数将它传递给视图时,它会分解成它的组件,因此$ data本身不再可用。 / p>