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

WBOY
Release: 2016-06-13 12:22:12
Original
1031 people have browsed it

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

/**<br />	 * Model Loader<br />	 *<br />	 * This function lets users load and instantiate models.<br />	 *<br />	 * @param	string	the name of the class<br />	 * @param	string	name for the model<br />	 * @param	bool	database connection<br />	 * @return	void<br />	 */<br />	public function model($model, $name = '', $db_conn = FALSE)
Copy after login


然后在看这个方法中是怎么实例化你的model类的:
			require_once($mod_path.'models/'.$path.$model.'.php');<br /><br />			$model = ucfirst($model);<br /><br />			$CI->$name = new $model();<br /><br />			$this->_ci_models[] = $name;<br />
Copy after login


看到喽,他只是简单的require 然后就 new 了,并且是没有参数的。
这个有点像的IoC中的container 可惜就是太那啥了。楼主可以做下改造
<br />$ref = ReflectionClass($modelName);<br />$modelInstance = $ref->newInstanceArgs(初始化的参数); <br />
Copy after login



------解决思路----------------------
总感觉直接改他的这个东西,你不如写个init方法

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!