问题描述
我是 Codeigniter 和 OOP PHP 的新手.
I'm new to Codeigniter and OOP PHP.
控制器:
public function index(){
$this->load->model('main_model');
$planet = $this->main_model->solar();
$this->load->view('main_view', $planet);
}
如果 echo $planet
在控制器中,它会做它应该做的事情.如果我在视图中 echo $planet
得到一个未定义的变量错误.$planet
不是数组.为什么 $planet
变量没有传递给视图?
If echo $planet
in the controller it does what it's supposed to do. If I echo $planet
in the view I get an undefined variable error. $planet
is not an array. Why isn't the $planet
variable being passed to the view?
我知道这是一个简单而基本的问题,我很尴尬,因为我无法弄清楚自己做错了什么.
I know this is a simple and basic question and I'm embarrassed that I can't figure out what I'm doing wrong.
好的,经过更多的摆弄,我开始工作了.变量格式化为数组后,只能从控制器传递到视图吗?
Okay, after more fiddling around, I got it to work. Can variables only be passed from Controller to View when they're formatted as an array?
推荐答案
您必须将数组传递给视图.CodeIgniter 会自动为您提供 $planet
.
You have to pass an array to the view. CodeIgniter automatically makes $planet
available to you.
$data = array('planet' => $planet);
$this->load->view('main_view', $data);
有了这个,您可以在视图中使用 $planet
.
With this you can use $planet
in your view.
例如,如果您执行以下操作:
E.g., if you do the following:
$data = array('foo' => 'Hello', 'bar' => 'world');
$this->load->view('main_view', $data);
$foo
和 $bar
将在您的视图中可用.数组中的键值对会自动转换为视图中的变量.
$foo
and $bar
will be available in your view. The key-value pairs in the array are automatically converted to variables in the view.
这篇关于将变量从控制器传递到 CodeIgniter 中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!