1. 实现过程
1) 上一节讲述了 View 视图的加载过程,它是在 Loader 类中加载的,并通过 Include 语句进行包含。那么为了在 View 中传递变量,只需要在 include 语句所在环境的变量列表中加入这些变量即可。
2) 另外必须考虑到可以加载多个视图,所以还要保证在前面加载视图传入的变量,后面也可以访问。
// 非常重要 if (is_array($_ci_vars)) { $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); } extract($this->_ci_cached_vars);
注意必须定义成员变量 $_ci_cached_vars
2. 测试
修改 test_view.php ,在标题下输出 $info
My First View Welcome, we finally met by MVC, my name is Zhangzhenyu!
那么相应在控制器函数中,也要改为
class welcome extends CI_Controller { function hello() { echo 'My first Php Framework!'; } function saysomething($str) { $this->load->model('test_model'); $info = $this->test_model->get_test_data(); $data['info'] = $info; $this->load->view('test_view', $data); }}
3. 测试
访问
可以看到输出如下
Welcome, we finally met by MVC, my name is Zhangzhenyu!
People you want in our model is Zhangzhenyu