【问题标题】:CodeIgniter accesing CI super object in core class constructorCodeIgniter 在核心类构造函数中访问 CI 超级对象
【发布时间】:2012-11-03 18:59:52
【问题描述】:

我在 application/core/MY_Lang.php 中有核心类,这个类扩展了 CI_Lang 类,并覆盖了基类的构造函数:

class MY_Lang extends CI_Lang {
    function __construct()
    {
        parent::__construct();
    }
}

如何从我的类的构造函数访问数据库对象。

我尝试访问 CI 超级对象,但类 CI_Controller 暂时没有加载

    if (class_exists('CI_Controller'))
    {
        $this->CI =& get_instance();
    }

【问题讨论】:

  • 您是否尝试加载数据库对象? $this->load->database();
  • 查看基础 CI_Lang 类,似乎 get_instance() 至少被使用过一次,因此在 Lang 类中使用它必须是有效的。您是否确保仅在调用父构造函数之后使用 get_instance()
  • 实际上,您是否尝试过调用 get_instance() 而不首先确保 CI_Controller 存在?我承认,我不确定 get_instance() 依赖于什么,但看起来他们只是在 CI_Lang 中调用它而没有进行任何额外的检查。

标签: php codeigniter


【解决方案1】:

好的,看来我只是调用 get_instance() 是错误的。

但是我发现了一个类似的帖子,它建议使用 post_controller_constructor“钩子”来调用你的函数

请看这里:CodeIgniter: get_instance inside My_Lang

代码点火器钩子的文档在这里:http://ellislab.com/codeigniter/user_guide/general/hooks.html

所以我猜想在你的 application/config/hooks.php 文件中你想添加这样的东西:

$hook['post_controller_constructor'] = array(
                                'class'    => 'MY_Lang',
                                'function' => '__construct',
                                'filename' => 'MY_Lang.php',
                                'filepath' => 'core',
                                'params'   => array()
                                );

我尚未对此进行测试,但如果您还没有完全使用它,请告诉我,我可以进行适当的测试。

当然,在你指定的函数中,你想调用 get_instance() 然后加载数据库库并做任何你想做的工作。

【讨论】:

    【解决方案2】:

    你只需要使用$this->CI =& get_instance();,你不需要其他代码,因为你有if (class_exists('CI_Controller')) { ... }

    这将允许您使用 CI 调用,例如 $this->CI->load->view$this->CI-load->lang 等。

    虽然我从未使用过 CI 挂钩,但我认为这不是您的情况所必需的,$this->CI =& get_instance(); 应该可以正常工作。

    【讨论】:

    • 你试过在本地机器上测试吗?
    • 确实在 Code Igniter 的本地副本上尝试了这个。对我来说,在 MY_Lang 类中,它不起作用。
    猜你喜欢
    • 2011-08-09
    • 2013-06-20
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多