2012-09-06 87 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

謝謝!有點遲,是第一個雖然:) –