在CodeIgniter中将变量从控制器传递到视图 [英] Passing variable from controller to view in CodeIgniter
问题描述
我刚接触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
在控制器中它做它应该做什么。如果I 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.
编辑:好吧,经过更多的fiddling,我得到它的工作。
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
例如,如果您执行以下操作:
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中将变量从控制器传递到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!