当前位置: 代码迷 >> PHP >> codeigniter中,Model构造函数能不能带参数,如果能如何调用
  详细解决方案

codeigniter中,Model构造函数能不能带参数,如果能如何调用

热度:45   发布时间:2016-04-28 17:15:08.0
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.
 *
 * @param string the name of the class
 * @param string name for the model
 * @param bool database connection
 * @return void
 */
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方法
  相关解决方案