【问题标题】:Calling a model in a Helper file using codeigniter使用 codeigniter 在 Helper 文件中调用模型
【发布时间】:2013-12-06 12:13:20
【问题描述】:

我想编写一个函数来加载帮助文件中的下拉菜单,因此我想在帮助文件中使用我的模型。

当我使用它时,它给了我错误:

$this->load->model("news_model");

错误:

Fatal error: Using $this when not in object context in C:\xampp\test\application\helpers\component_helper.php on line 6

我的方法:

function dropdown($Class,$Attribute)
{
$Output=NULL;
$ClassName=$Class."_model";
$this->load->model($ClassName);
$FullData=$ClassName->get();
foreach ($FullData as $Data) 
{
    $Output.='<option value="'.$Data->Id.'">'.$Data->$Attribute.'</option>';
}
return $Output;
}

谢谢

【问题讨论】:

  • 第 6 行是指 $this->load->model 吗?

标签: php codeigniter


【解决方案1】:

查看这篇文章:

function my_helper()
{
    // Get a reference to the controller object
    //$CI = get_instance();
    // use this below
    $CI = &get_instance();

    // You may need to load the model if it hasn't been pre-loaded
    $CI->load->model('my_model');

    // Call a function of the model
    $CI->my_model->do_something();
}

https://stackoverflow.com/a/2479485/1570901

【讨论】:

  • 当我使用 $CI = getInstance();它给了我错误:致命错误:在第 6 行调用 C:\xampp\test\application\helpers\component_helper.php 中的未定义函数 getInstance()
  • $CI = get_instance();不是:getInstance();
【解决方案2】:

辅助函数是函数。这意味着它们不受对象或类的约束。 $this 因此不可用!

您必须从其他地方获取 CodeIgniter-Core 的实例!

CodeIgniter 为此提供了一个get_instance(); 函数:

$CI = get_instance();

现在你有没有$this-&gt;load 等。 将$this 替换为$CI 以调用CodeIgniter Core!

顺便说一句,您将模型称为错误。您必须通过 CI 核心访问它:

 $CI->$Classname->get();

【讨论】:

  • 当我使用 $CI = getInstance();它给了我错误:致命错误:在第 6 行调用 C:\xampp\test\application\helpers\component_helper.php 中的未定义函数 getInstance()
【解决方案3】:

这里是你的代码更正:

function dropdown($Class,$Attribute)
{
$CI = get_instance();
$Output=NULL;
$ClassName=$Class."_model";
$CI->load->model($ClassName);
$FullData=$ClassName->get();
foreach ($FullData as $Data) 
{
    $Output.='<option value="'.$Data->Id.'">'.$Data->$Attribute.'</option>';
}
return $Output;
}

现在不要使用 $this,而是始终在此方法中使用 $CI。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多