天天看点

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

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方法不存在传初始化值的参数

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

相关文章

相关视频