我把这段代码放在一个模型类的构造器中,基于CI的教程,它声明如果你把它放在那里,数据库连接以后可以在那个类中全局使用。由于某些原因,它无法工作,应用程序在代码的该部分崩溃。我的数据库配置很好,因为当我把它放到控制器中时,我可以很好地获取数据库信息。
发布于 2011-07-13 11:21:18
您是在父类的构造函数之前还是之后执行此操作?
public function __construct()
{
// placing it here fails: $this has no `load` property yet.
// $this->load->database(); <!-- NO WAY JOSÉ!
parent::__construct();
// placing it here should work as the parent class has added that property
// during it's own constructor
$this->load->database();
}另一方面,您可以更明确地表示:
public function __construct()
{
// Doesn't matter where this goes:
// grab the controller directly
$CI =& get_instance(); // & is not strictly necessary, but still...
// force the loader to load the database.
$CI->load->database();
// directly assign it.
$this->db = $CI->db;
// continue on your merry way
parent::__construct();
}发布于 2011-07-13 00:40:54
你不需要初始化它。最好将其配置为
像这样的application - config - autoload.php文件
$autoload['libraries'] = array('database');发布于 2011-07-13 04:01:07
加载数据库对象的代码行是:
$this->load->database();然后使用名称db引用数据库对象,如下所示:
$this->db->method_name();正如前一篇文章所指出的,如果你打算跨多个模型使用数据库,你应该在你的autoload.php配置文件中自动加载库。
https://stackoverflow.com/questions/6667776
复制相似问题