codeigniter中,Model建構函式能不能帶參數,如果能如何調用

來源:互聯網
上載者:User
codeigniter中,Model建構函式能不能帶參數,如果能怎麼調用?
如題

codeigniter中,Model建構函式能不能帶參數,如果能怎麼調用?


如:
class Test extends CI_Model{

function __construct( $id){
$q = $this->db->query("Select * From test Where id='". $id."'")->row_array();
$this->name = $q["name"];
}

}

調用時,怎麼將id傳進model並且直接初始化
$this->load->model("Test", "mytest");
------解決思路----------------------
看看那個 model 方法是怎麼寫的
------解決思路----------------------
是嗎?
$this->load->model("Test", "mytest");
這個 model 方法的定義你給出了嗎?
------解決思路----------------------
貌似 CI 裡面不支援這麼傳參
------解決思路----------------------
不能
首先loader->model方法不存在傳初始化值的參數
/**
* Model Loader
*
* This function lets users load and instantiate models.
*
* @paramstringthe name of the class
* @paramstringname for the model
* @parambooldatabase connection
* @returnvoid
*/
public function model($model, $name = '', $db_conn = FALSE)


然後在看這個方法中是怎麼執行個體化你的model類的:
require_once($mod_path.'models/'.$path.$model.'.php');

$model = ucfirst($model);

$CI->$name = new $model();

$this->_ci_models[] = $name;


看到嘍,他只是簡單的require 然後就 new 了,並且是沒有參數的。
這個有點像的IoC中的container 可惜就是太那啥了。樓主可以做下改造

$ref = ReflectionClass($modelName);
$modelInstance = $ref->newInstanceArgs(初始化的參數);



------解決思路----------------------
總感覺直接改他的這個東西,你不如寫個init方法
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.