问题
I'm receiving the following errors whilst trying to implement a very simple model controller in codeigniter. I'm new to the framework but as far as I can see this should work.
I've also tried auto loading the model. I am autoloading the database library.
Message: Undefined property: User::$user_model
Fatal error: Call to a member function get_user() on a non-object
The model
class User_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_user()
{
return "test";
}
}
The controller
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function index()
{
$this->load->model('User_model');
$data['value'] = $this->User_model->get_user();
$this->load->view('user_edit', $data);
}
}
Thanks
回答1:
just use some thing like this, $this->load->model('user_model');
don't use $this->load->model('User_model');
and make sure you have same name, when the model name like user_mode.php
and the class like class User_model extends CI_Model(){}
so when you call it from controller use the lower case look like your model name user $this->load->model('user_model')
回答2:
I think i've found the problem. I had some additional setter methods in my user controller which i've used all the time, didnt think they would be a problem.
public function __set($key, $value)
{
// Check to see that the requested attribute exists and then assign the value
if (property_exists($this, $key))
{
$this->$key = $value;
}
}
turns out I needed to take away one of the underscores as codeigniter doesn't like it.
public function _set($key, $value)
I should have really included the full class but I was trying to keep it as simple as possible!
来源:https://stackoverflow.com/questions/8440226/codeigniter-undefined-property-when-loading-a-model