2012-09-06 82 views
0

我有两个模型,第一个模型依赖于第二个模型,我需要从第一个构造函数的第二个模型中调用方法。CodeIgniter使用模型的构造函数

到目前为止,我有这样的:

用户

class User extends CI_Model { 

    protected $_attributes = array(); 

    function __construct() { 
     parent::__construct(); 
     $this->load->model('musers'); 
     foreach($this->musers->GetProfile() as $key => $val) { 
      $this->_attributes[$key] = $val; 
     } 
    } 

    function __set($key, $val) { 
     return $this->_attributes[$key] = $val; 
    } 

    function __get($key) { 
     return $this->_attributes[$key]; 
    } 
} 

我已经把这种模式在autoload配置文件,这里就是我得到:

A PHP Error was encountered 
Severity: Notice 
Message: Undefined index: load 
Filename: models/user.php 
Line Number: 20 

Fatal error: Call to a member function model() on a non-object in path\to\models\user.php on line 9 

还有什么奇怪 - 第一个错误(通知)是指行return $this->_attributes[$key];,而它肯定应该参考行$this->load->model('musers');

我曾尝试在user模型之前自动加载模型musers,但没有任何帮助。我试图寻找这个,但不能很好地制定查询,我敢肯定有我的问题的解决方案。

据我所知,这是因为第二个模型的构造函数在CodeIgniter管理加载加载器类本身之前调用,但这很奇怪。

回答

4

尝试:

function __construct() { 
    parent::__construct(); 
    $CI =& get_instance(); 
    $CI->load->model("musers", "musers"); 
    foreach($CI->musers->GetProfile() as $key => $val) { 
     ...... 
} 

    ...... 
+0

主席先生,你是我今天的主角,荣誉给你!没想到,尽管我现在不断地在写图书馆。 –

+0

@Vlakarados很高兴你得到它:) :) –

1

尝试这样

$CI = &get_instance();//you need to define the instance for loading the second model musers 
$CI->load->model('musers'); 
+0

谢谢!有点迟,是第一个虽然:) –