我是初学PHP和codeigniter学习者。
从Controller加载后,有一个模型不起作用,但从另一个模型加载时效果很好。
我正在为用户构建应用以获取反馈。用户可能会向观众提出几个问题。
从编码的角度来看,我有一个扩展CI_Controller的基本控制器“MY_Controller
”。
然后我有2个控制器,扩展我的控制器 - 主页(用户将看到的主页)和问题(查看问题的详细信息)。
我有两个主要模型:user_model
和question_model
当我从user_model中加载question_model时,一切顺利,程序运行正常。
但是当我从Question控制器中加载question_model时,它运行构造函数(我已经做了一个echo来检查)并且它完成了构造函数(我再次回应检查),但是当我调用一个方法时question_model我收到错误:
Fatal error: Call to a member function initialize() on a non-object in /Users/jaimequintas/Dropbox/3 CODIGO/feedbacking/application/controllers/question.php on line 17
有人可以帮我吗?我一直在为此奋斗超过一天,无论如何我无法解决它。
我的基本控制器:
class MY_controller extends CI_Controller{
public function index()
{
$this->session->set_userdata('user_id', 8); //this is here just to initialize a user while in DEV
$this->prepare_user(); //populates user with DB info
}
我的问题控制器(不能使用$ this-> question_model方法的那个)
class Question extends MY_Controller {
public function index(){
parent::index();
$active_question = $this->uri->segment(2,0);
$this->load->model('Question_model'); //this line runs well, as an echo statement after this gets printed
$this->Question_model->initialize($active_question); //this is the line that triggers the "can't use method error"
$this->Question_model->get_answers_list();
这是Question_model,其方法无法从控制器调用。
class Question_model extends CI_Model {
public $question_id;
public $question_text;
public $vote_count;
public $activation_date;
public $status; //Draft, Active, Archived
public $question_notes; //user notes
public $question_url; //the segment that will be added to codeigniter url feedbacking.me/"semgent"
public $answers_list; //array with answer objects
public $last_vote; //date of the last vote
public $vote_count_interval; //this is not computed with initialize, must call method when needed
public function __construct()
{
parent::__construct();
}
public function initialize($question_id)
{
//populate question from DB with: question_id, question_text, vote_count, activation_date, status
// if $question_id ==0 creates an empty question (should be followed by create_question)
$this->question_id = $question_id;
$this->get_question_by_id();
$this->get_question_votes();
}
最后是User_model。我只把它放在这里,因为当这个模型加载Question_model时,一切正常。
class User_model extends CI_Model {
public $user_id;
public $user_email;
public $user_name;
public $plan_id;
public $questions_list; //array with question objects
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function initialize($user_id)
{
//populates user_info and question_list
$this->user_id = $user_id;
$this->get_user_by_id();
$this->get_user_questions(); //this line calls the Question_model and works fine
}
答案 0 :(得分:1)
在模型中加载模型时,需要获取代码点火器的实例(而不是$ this):
$CI =& get_instance();
$CI->load->model('Question_model');
$CI->Question_model->initialize($active_question);
$CI->Question_model->get_answers_list();