我正在尝试使用最新的CodeIgniter框架学习PHP,但我遇到了一些问题.我不知道我是否只是运气不好或者我错过了一些基本概念.
这是我的View/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
</head>
<body>
<?php foreach($forums as $f): ?>
<table>
<tr><td style="background-color:#ccc; font-weight:bold border: 1px solid black;">
<?php echo $f['name']; ?>
</td></tr></table><br />
<?php endforeach; ?>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是我的Models/index.php:
class Index_Model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function getIndexListing(){
$query = $this->db->query('Select name from Forums where parentid=0 order by sortorder asc');
$rows = $query->result_array();
$query->free_result();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的Controllers/index.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Index extends CI_Controller {
function __construct()
{
parent::__construct();
// load users model
if (! isset($this->Index_Model))
{
// $this->load->model( 'Index_Model' );
}
}
function index()
{
$data['forums']= $this->Index_Model->getIndexListing();
$data['title'] = 'Welcome!';
$this->load->view('index.php', $data);
}
}
Run Code Online (Sandbox Code Playgroud)
问题:我无法弄清楚如何打电话getIndexListing()
.当我这样做时,我得到了错误Undefined property: Index::$Index_Model
.但是当我取消注释时$this->load->model( 'Index_Model' );
,我的内存异常就会消失.
什么是正确的呼叫方式,getIndexListing()
所以我可以填充我的页面?我错误地命名了我的课程或文件吗?
首先,您需要更改控制器名称,因为索引是保留名称http://codeigniter.com/user_guide/general/reserved_names.html
然后你必须有两个不同的控制器类和模型类名称,它们不能相同,因为你不能在同一个命名空间中有两个同名的类.所以,假设你的控制器是什么,那么拥有像whatever_model这样的模型类是一种好习惯