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方法