$这 - >负载>分贝();在类构造函数中初始化?

时间:2011-07-12 16:36:03

标签: codeigniter

我将此代码放在模型类的构造函数中,基于CI的教程,它指出如果你把它放在那里,那么数据库连接可以在该类中全局使用。由于某种原因,它不起作用,应用程序崩溃在代码的那一部分。我的数据库配置很好,因为当我把它放在控制器中时,我能够获得数据库信息。

3 个答案:

答案 0 :(得分:2)

你是在父类的构造函数之前或之后做的吗?

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();
}

我相信显式解决方案一次解决了PHP 4项目中的一些问题,但它在技术上有点过分。

答案 1 :(得分:1)

你不需要初始化它。更好地配置为
application - config - autoload.php这样的文件为

   $autoload['libraries'] = array('database');

答案 2 :(得分:0)

加载数据库对象的代码行是:

$this->load->database();

然后使用名称db引用数据库对象,如下所示:

$this->db->method_name();

正如前一篇文章所指出的那样,如果要在多个模型中使用数据库,则应该在autoload.php配置文件中自动加载库。

相关问题