php codeigniter 模型错误:未定义的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3440839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
codeigniter model error: Undefined property
提问by Vina
Possible Duplicate:
Error : get property of non-object
可能的重复:
错误:获取非对象的属性
I am new to codeigniter model, i try to follow steps in docs to load all user registered in my db.
我是 codeigniter 模型的新手,我尝试按照文档中的步骤加载在我的数据库中注册的所有用户。
This is my model: user.php
这是我的模型: user.php
class User extends Model {
function user() {
parent::Model();
}
function alluser() {
$query = $this->db->query("select * from user limit 0,5"); //Line 30 error as in my IDE located in this line
return $query->result();
}
}
This is my controller: home.php
这是我的控制器: home.php
class home extends Controller {
function index() {
parent::Controller();
}
function alluser() {
$this->load->model('User');
$result = $this->User->showusers();
if ($result->num_rows()>0) {
foreach ($result as $row) {
echo "ID:".$row->userid." ".$row->userpenname."<br />";
echo $row->userfirstname." ".$row->userlastname."<br />";
}
}
}
}
it showing error:
它显示错误:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: User::$db
Filename: models/user.php
Line Number: 30
Fatal error: Call to a member function query() on a non-object in
G:\xampp\htdocs\fiksi\system\application\models\user.php on line 30
致命错误:
在第 30 行调用G:\xampp\htdocs\fiksi\system\application\models\user.php中非对象的成员函数 query()
Line 30 see comment above...
第 30 行见上面的评论......
回答by Nacho
You have to load the db library first. In autoload.php
add :
您必须先加载 db 库。在autoload.php
添加:
$autoload['libraries'] = array('database');
Also, try renaming User model class for "User_model".
另外,尝试为“User_model”重命名用户模型类。
回答by Vina
It solved throung second parameter in Model load:
它解决了模型加载中的第二个参数:
$this->load->model('user','User');
first parameter is the model's filename, and second it defining the name of model to be used in the controller:
第一个参数是模型的文件名,第二个参数定义了要在控制器中使用的模型的名称:
function alluser()
{
$this->load->model('User');
$result = $this->User->showusers();
}
回答by John Hu
function user() {
parent::Model();
}
=> class name is User, construct name is User.
=> 类名是用户,构造名是用户。
function User() {
parent::Model();
}