gpt4 book ai didi

php - 将变量从 Controller 传递到 CodeIgniter 中的 View

转载 作者:IT王子 更新时间:2023-10-29 00:14:45 27 4
gpt4 key购买 nike

我是 Codeigniter 和 OOP PHP 的新手。

Controller :

public function index(){
$this->load->model('main_model');
$planet = $this->main_model->solar();
$this->load->view('main_view', $planet);
}

如果 Controller 中的 echo $planet 它会执行它应该执行的操作。如果我在 View 中 echo $planet 我会得到一个 undefined variable 错误。 $planet 不是数组。为什么不将 $planet 变量传递给 View ?

我知道这是一个简单而基本的问题,我很尴尬,因为我不知道自己做错了什么。

编辑:好的,经过更多的摆弄,我开始工作了。变量只能在格式化为数组时从Controller传递到View吗?

最佳答案

您必须将数组传递给 View 。 CodeIgniter 自动使 $planet 可供您使用。

$data = array('planet' => $planet);
$this->load->view('main_view', $data);

有了它,您可以在您的 View 中使用 $planet

例如,如果您执行以下操作:

$data = array('foo' => 'Hello', 'bar' => 'world');
$this->load->view('main_view', $data);

$foo$bar 将在您的 View 中可用。数组中的键值对自动转换为 View 中的变量。

关于php - 将变量从 Controller 传递到 CodeIgniter 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294527/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com